2017-10-16 80 views
1

當遇到重複值時,我無法通過「索引」函數的限制。Python:返回每個重複值的字典索引

具體而言,對於字典中的重複數據(例如下面的例子)中的給定值,是否有辦法檢索值的每次出現的索引,而不僅僅是第一次?

example_dict={'ABAB': [9,10,6,6,6]} 
example_dict['ABAB'].index(6) # returns 2 

我的目標是在以後的工作中使用這些指標。所以我需要知道9是索引0,10是索引1,而6是索引2,3和4的值(不只是2)。

有人可以提供一個小貼士,爲此解決方法?非常感謝您的幫助。

回答

2

這應該做的伎倆:

>>> example_dict = {'ABAB': [9,10,6,6,6]}                            
>>> [i for i, x in enumerate(example_dict['ABAB']) if x == 6] 
[2, 3, 4]  
+0

謝謝您的幫助。 –

2

嘗試列表理解:

[i for i, x in enumerate(example_dict['ABAB']) if x == 6] 

For more discussion.

+1

謝謝你的幫助。 –

0
zz = {'a', [1,2,3,6,6,6,3,5,7,7,9,2]} 
y = { } 
K = [ ] 
for z in zz : 
    for i in zz[z] : 
     y.setdefault(i , [zz[z].index(i)]) 
     ii = zz[z].index(i) 
     zz[z][ii] = None 
     if i not in k : 
      k.append(i) 
     if i in zz[z] and i in k : 
      y[i].append(zz[z].index(i)) 
print(y) 
+0

這應該給你每個值的索引重複 – Uraniumkid30