Python列表中重复项的索引

82

有没有人知道如何在python列表中获取重复项的索引位置? 我尝试过这样做,但它只给出了该项在列表中第一次出现的索引。

List = ['A', 'B', 'A', 'C', 'E']

我希望它能给我:

index 0: A   
index 2: A

26
请注意,Python风格指南指出,变量的名称不应使用大写字母,也要避免使用内置类的名称,如list。 - Lauritz V. Thaulow
6
“List”与“list”是不同的。 - martineau
13
@martineau:我知道,但我想确认他没有仅通过将变量转换为小写来解决大写问题。 - Lauritz V. Thaulow
这是在询问如何获取序列中重复出现项的索引,答案在这里;以及如何查找序列中的重复项,答案在这里 - mkrieger1
23个回答

-1
a= [2,3,4,5,6,2,3,2,4,2]
search=2
pos=0
positions=[]

while (search in a):
    pos+=a.index(search)
    positions.append(pos)
    a=a[a.index(search)+1:]
    pos+=1

print "search found at:",positions

-1

我会提到处理列表中重复元素更为显然的方法。在复杂性方面,字典是首选,因为每个查找的时间复杂度都为O(1)。如果你只关心重复元素,可以有更巧妙的方法...

my_list = [1,1,2,3,4,5,5]
my_dict = {}
for (ind,elem) in enumerate(my_list):
    if elem in my_dict:
        my_dict[elem].append(ind)
    else:
        my_dict.update({elem:[ind]})

for key,value in my_dict.iteritems():
    if len(value) > 1:
        print "key(%s) has indices (%s)" %(key,value)

输出以下内容:

key(1) has indices ([0, 1])
key(5) has indices ([5, 6])

-3

我来简单解释一下:

i = [1,2,1,3]
k = 0
for ii in i:    
if ii == 1 :
    print ("index of 1 = ", k)
k = k+1

输出:

 index of 1 =  0

 index of 1 =  2

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接