如何在列表中查找重复项及其索引?

时间:2019-03-15 10:11:37

标签: python python-3.x

我有一个列表

l=['a','b','c','c','a','d']

输出应返回列表中所有重复的元素及其索引

输出:

out = {a:['0','4'],c:['2','3']}

我尝试过

def nextDuplicates(c):
    dupl_c = dict()
    sorted_ind_c = sorted(range(len(c)), key=lambda x: c[x])
    for i in xrange(len(c) - 1):
        if c[sorted_ind_c[i]] == c[sorted_ind_c[i+1]]:
            dupl_c[ sorted_ind_c[i] ] = sorted_ind_c[i+1]
    return dupl_c

5 个答案:

答案 0 :(得分:1)

dict的理解与list的理解结合使用(即使发生两次以上):

l = ["a", "b", "c", "c", "a", "d"]
out = {el: [i for i, x in enumerate(l) if x == el] for el in l if l.count(el) > 1}

在您的预期输出中,我看到索引是字符串。我不明白为什么,但是如果您真的希望将它们作为字符串,请将i for i, x替换为str(i) for i, x

More on list comprehensions

答案 1 :(得分:1)

尝试一下:

l=['a','b','c','c','a','d']
o = {}
for i in range(len(l)):
    if (l[i] in o):
        o[l[i]].append(i)
    else:
        o[l[i]] = [i]
print({key:val for key, val in o.items() if len(val) > 1})

答案 2 :(得分:1)

使用collections.defaultdict + set迭代可以更快地查找大于1的计数。

from collections import defaultdict

l = ['a','b','c','c','a','d']

result = defaultdict(list)

for x in set(l):
    if l.count(x) > 1:
        result[x].extend([i for i, y in enumerate(l) if y == x])

print(result)
# defaultdict(<class 'list'>, {'a': [0, 4], 'c': [2, 3]})

答案 3 :(得分:1)

您可以使用此dict理解

l = ["a", "b", "c", "c", "a", "d"]
out = {ele: [str(i) for i, x in enumerate(l) if x == ele] for ele in set(l) if l.count(ele) > 1}

# Output : {'c': ['2', '3'], 'a': ['0', '4']}

与其使用集合对列表本身进行迭代,反而可以改善性能,尤其是当重复项很多时。

在期望的输出中,您需要一个str列表作为值。如果需要整数,则可以使用i代替str(i)

答案 4 :(得分:0)

l=['a','b','c','c','a','d']

result = {}

for element in l:
    if element not in result:
         indexes = [i for i, x in enumerate(l) if x == element]

         if len(indexes) > 1:
              result[element] = indexes

print(result)

遍历列表,检查元素是否在字典中已经存在。如果没有,则获取该元素的所有索引并将该元素附加到字典中。

相关问题