gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 09:32:29 25 4
gpt4 key购买 nike

我有一个 list

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

最佳答案

使用 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]})

关于python - 如何在列表中查找重复项及其索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55180204/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com