PyN*_*bie 1 python indexing containers list
我一直在寻找一个配方/示例来索引元组列表,而不需要修改装饰,排序,不合理的方法.
例如:
l=[(a,b,c),(x,c,b),(z,c,b),(z,c,d),(a,d,d),(x,d,c) . . .]
Run Code Online (Sandbox Code Playgroud)
我一直在使用的方法是使用第二个元素的defaultdict构建一个字典
from collections import defaultdict
tdict=defaultdict(int)
for myTuple in l:
tdict[myTuple[1]]+=1
Run Code Online (Sandbox Code Playgroud)
然后我必须为列表中的每个项目构建一个仅包含元组中第二项的列表.虽然有很多方法可以达到目的,但是一个简单的方法是:
tempList=[myTuple[1] for myTuple in l]
Run Code Online (Sandbox Code Playgroud)
然后生成tdict中每个项目的索引
indexDict=defaultdict(dict)
for key in tdict:
indexDict[key]['index']=tempList.index(key)
Run Code Online (Sandbox Code Playgroud)
显然,这似乎不是Pythonic.我一直试图找到一些例子或见解,认为我应该能够使用神奇的东西直接获得索引.到目前为止没有这样的运气
请注意,我知道我可以更直接地采用我的方法,而不是生成tdict.
输出可以是带索引的字典
indexDict={'b':{'index':0},'c':{'index':1},'d':{'index':4},. . .}
Run Code Online (Sandbox Code Playgroud)
在从Nadia的回答中学到很多东西后,我认为答案是肯定的.
虽然她的反应有效但我觉得它比需要的更复杂.我会简单的
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
Run Code Online (Sandbox Code Playgroud)
这将生成您想要的结果
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}
Run Code Online (Sandbox Code Playgroud)
如果你坚持使用字典来表示索引:
dict((myTuple[1], {'index': index}) for index, myTuple in enumerate(l))
Run Code Online (Sandbox Code Playgroud)
结果将是:
{2: {'index': 0}, 4: {'index': 2}, 5: {'index': 1}}
Run Code Online (Sandbox Code Playgroud)
编辑 如果你想处理密钥冲突,那么你必须像这样扩展解决方案:
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}
Run Code Online (Sandbox Code Playgroud)
编辑2
一个更通用和紧凑的解决方案(在类似的定义中排序)
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}
Run Code Online (Sandbox Code Playgroud)
因此,您的问题的答案是肯定的:Python中有一种方法可以通过容器的元素索引容器列表(元组,列表,字典)而无需预处理.但是你将结果存储在字典中的要求使得它不可能成为一个班轮.但这里没有预处理.该列表仅迭代一次.