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

2024-04-20 05:29:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一张单子

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

Tags: lambdakey元素列表forlendefrange
3条回答

一个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}

我在预期的输出中看到索引是字符串。我不明白为什么,但是如果你真的想把它们作为字符串,用str(i) for i, x替换i for i, x。你知道吗

More on list comprehensions

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)

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

使用collections.defaultdict+a 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]})

相关问题 更多 >