繁体   English   中英

Python中是否有一种方法可以通过容器的元素为容器列表(元组,列表,字典)建立索引?

[英]Is there a way in Python to index a list of containers (tuples, lists, dictionaries) by an element of a container?

我一直在寻找一个食谱/示例来索引元组列表,而无需修改修饰,排序,修饰的方法。

例如:

l=[(a,b,c),(x,c,b),(z,c,b),(z,c,d),(a,d,d),(x,d,c) . . .]

我一直在使用的方法是使用第二个元素的defaultdict构建字典

from collections import defaultdict

tdict=defaultdict(int)

for myTuple in l:
    tdict[myTuple[1]]+=1

然后,我必须为列表中的每个项目建立一个仅由元组中的第二个项目组成的列表。 尽管有多种方法可以实现,但一种简单的方法是:

tempList=[myTuple[1] for myTuple in l]

然后生成tdict中每个项目的索引

indexDict=defaultdict(dict)
for key in tdict:
    indexDict[key]['index']=tempList.index(key)

显然,这似乎不是Python风格的。 我一直在尝试寻找示例或见解,以为我应该能够使用一些神奇的方法直接获取索引。 到目前为止还没有这样的运气。

请注意,我知道我可以更直接地采用我的方法,而不会产生问题。

输出可能是带有索引的字典

indexDict={'b':{'index':0},'c':{'index':1},'d':{'index':4},. . .}

从纳迪亚的回答中学到很多东西后,我认为答案是否定的。

尽管她的回应有效,但我认为这比需要的要复杂。 我只会

 def build_index(someList):
    indexDict={}
    for item in enumerate(someList):
        if item[1][1] not in indexDict:
           indexDict[item[1][1]]=item[0]
    return indexDict

这将产生您想要的结果

dict((myTuple[1], index) for index, myTuple in enumerate(l))

>>> l = [(1, 2, 3), (4, 5, 6), (1, 4, 6)]
>>> dict((myTuple[1], index) for index, myTuple in enumerate(l))
{2: 0, 4: 2, 5: 1}

如果您坚持使用字典来表示索引:

dict((myTuple[1], {'index': index}) for index, myTuple in enumerate(l))

结果将是:

{2: {'index': 0}, 4: {'index': 2}, 5: {'index': 1}}

编辑如果要处理按键冲突,则必须扩展解决方案,如下所示:

def build_index(l):
    indexes = [(myTuple[1], index) for index, myTuple in enumerate(l)]
    d = {}
    for e, index in indexes:
        d[e] = min(index, d.get(e, index))
    return d

>>> l = [(1, 2, 3), (4, 5, 6), (1, 4, 6), (2, 4, 6)]
>>> build_index(l)
{2: 0, 4: 2, 5: 1}

编辑2

以及更通用,更紧凑的解决方案(类似于sorted的定义)

def index(l, key):
    d = {}
    for index, myTuple in enumerate(l):
        d[key(myTuple)] = min(index, d.get(key(myTuple), index))
    return d

>>> index(l, lambda a: a[1])
{2: 0, 4: 2, 5: 1}

因此,您的问题的答案是肯定的:Python中有一种方法可以通过容器的元素对容器列表(元组,列表,字典)进行索引,而无需进行预处理。 但是您将结果存储在字典中的要求使得不可能成为一个衬里。 但是这里没有预处理。 该列表仅重复一次。

如果我认为这是您要问的...

l = ['asd', 'asdxzc']
d = {}

for i, x in enumerate(l):
    d[x] = {'index': i}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM