簡體   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