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
string_list = ['A', 'B', 'C', 'B', 'D', 'B']
pos_list = []
for i in range(len(string_list)):
    if string_list[i] = ='B':
        pos_list.append(i)
print pos_list

1
为了帮助 OP 解决当前的问题,可以在回答中添加一些解释说明。 - ρяσѕρєя K

1

这是一个好问题,有很多方法可以解决。

下面的代码是其中一种解决方案。

letters = ["a", "b", "c", "d", "e", "a", "a", "b"] 

lettersIndexes = [i for i in range(len(letters))] # i created a list that contains the indexes of my previous list
counter = 0 
for item in letters: 
    if item == "a": 
        print(item, lettersIndexes[counter]) 
    counter += 1 # for each item it increases the counter which means the index 

另一种获取索引的方法,但这次存储在列表中

letters = ["a", "b", "c", "d", "e", "a", "a", "b"] 
lettersIndexes = [i for i in range(len(letters)) if letters[i] == "a" ] 
print(lettersIndexes) # as you can see we get a list of the indexes that we want.

你好


1

已经有很多回复了,但我真的很喜欢这个解决方案,而且它非常快(它使用pandas.Series,因为它们比pd.DataFrames更快)。

这个解决方案的好处是它忽略了所有重复元素的第一个元素。

import numpy as np
import pandas as pd

lst = [0, 1, 1, 2, 2, 2, 3, 4, 5, 6, 6, 7, 8, 9, 9]
#index 0  1  2  3  4  5  6  7  8  9  10 11 12 13 14
#duplicates  |     |  |              |           |

indices = np.where(pd.Series(lst).duplicated())[0]

print(indices)
# [ 2  4  5 10 14]

0
使用基于 setdefault 实例方法的字典方法。
List = ['A', 'B', 'A', 'C', 'B', 'E', 'B']

# keep track of all indices of every term
duplicates = {}
for i, key in enumerate(List):
    duplicates.setdefault(key, []).append(i)

# print only those terms with more than one index
template = 'index {}: {}'
for k, v in duplicates.items():
    if len(v) > 1:
        print(template.format(k, str(v).strip('][')))    

备注: Counterdefaultdict和其他来自collections的容器类都是dict的子类,因此也共享setdefault方法。

0
def dup_list(my_list, value):
    '''
    dup_list(list,value)
        This function finds the indices of values in a list including duplicated values.

        list: the list you are working on

        value: the item of the list you want to find the index of

            NB: if a value is duplcated, its indices are stored in a list
            If only one occurence of the value, the index is stored as an integer.

            Therefore use isinstance method to know how to handle the returned value
    '''
    value_list = []
    index_list = []
    index_of_duped = []

    if my_list.count(value) == 1:
        return my_list.index(value)  
        
    elif my_list.count(value) < 1:
        return 'Your argument is not in the list'

    else:
        for item in my_list:
            value_list.append(item)
            length = len(value_list)
            index = length - 1
            index_list.append(index)

            if item == value:
                index_of_duped.append(max(index_list))

        return index_of_duped

# function call eg dup_list(my_list, 'john')

0
def duplicates(list,dup):
  a=[list.index(dup)]
  for i in list:
     try: 
        a.append(list.index(dup,a[-1]+1))
     except:
        for i in a:
           print(f'index {i}: '+dup)
        break
duplicates(['A', 'B', 'A', 'C', 'E'],'A')

  Output:
          index 0: A
          index 2: A

0
如果您想获取不同类型的所有重复元素的索引,可以尝试以下解决方案:
# note: below list has more than one kind of duplicates
List = ['A', 'B', 'A', 'C', 'E', 'E', 'A', 'B', 'A', 'A', 'C']
d1 = {item:List.count(item) for item in List}  # item and their counts
elems = list(filter(lambda x: d1[x] > 1, d1))  # get duplicate elements
d2 = dict(zip(range(0, len(List)), List))  # each item and their indices

# item and their list of duplicate indices
res = {item: list(filter(lambda x: d2[x] == item, d2)) for item in elems}

现在,如果你 print(res),你会看到这个:
{'A': [0, 2, 6, 8, 9], 'B': [1, 7], 'C': [3, 10], 'E': [4, 5]}

0

这里有一个适用于多个重复项的解决方案,您不需要指定任何值:

List = ['A', 'B', 'A', 'C', 'E', 'B'] # duplicate two 'A's two 'B's

ix_list = []
for i in range(len(List)):
    try:
        dup_ix = List[(i+1):].index(List[i]) + (i + 1) # dup onwards + (i + 1)
        ix_list.extend([i, dup_ix]) # if found no error, add i also
    except:
        pass
    
ix_list.sort()

print(ix_list)
[0, 1, 2, 5]

0
def find_duplicate(list_):
    duplicate_list=[""]

    for k in range(len(list_)):
        if duplicate_list.__contains__(list_[k]):
            continue
        for j in range(len(list_)):
            if k == j:
                continue
            if list_[k] == list_[j]:
                duplicate_list.append(list_[j])
                print("duplicate "+str(list_.index(list_[j]))+str(list_.index(list_[k])))

0
这里有很多很好的答案。我想再补充一下我的方法。我使用了collections模块中的Counter类,以更少的代码行数完成了这个任务。我还使用了range(len(list))作为使用enumerate函数的另一种方式。
import collections as col

lett_list = ['A', 'B', 'A', 'C', 'E']
lett_dict = {}
counter = col.Counter(lett_list)
elements = [i for i in counter] 
for elem in elements:
    lett_dict[elem]=[i for i in range(len(lett_list)) if lett_list[i]==elem]

print(lett_dict)

输出:{'A': [0, 2], 'B': [1], 'C': [3], 'E': [4]}

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