2009-05-27 37 views
1

我一直在尋找一個食譜/示例來索引元組列表,而不用修改裝飾,排序,未整理的方法。在Python中是否有方法通過容器的元素來索引容器列表(元組,列表,字典)?

例如:

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的。我一直在試圖找到例子或見解,認爲我應該能夠使用神奇的東西來直接獲取索引。目前沒有這樣的運氣。

請注意,我知道我可以更直接地採取我的方法,而不是生成tdict。

輸出可能是一個字典,該指數

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

借鑑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 
+1

我很困惑你想要做什麼。你想要的輸出是什麼?你的代碼不工作 - 計數應該在行「tdict [myTuple [1]] + = count」是什麼? – 2009-05-27 21:27:55

+0

你能提供一個預期的輸出或結構的例子嗎? – 2009-05-27 21:28:00

+0

對不起 - 每次我創建一個字典來獲取一個項目的數量,我總是寫入+ =計數,然後將其修正爲+ = 1。我有一個腦細胞。 – PyNEwbie 2009-05-27 21:38:56

回答

5

,這將產生的結果你想

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} 

EDIT 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中有一種方法可以通過容器的元素對容器列表(元組,列表,字典)進行索引,而無需預處理。但是,將結果存儲在字典中的請求使得它不可能成爲單行文本。但是這裏沒有預處理。該列表僅迭代一次。

0

如果我認爲這是你問的問題...

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

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