【381】python 获取列表中重复元素的索引值

参考:获取python的list中含有重复值的index方法_python_脚本之家  

核心思想:建立字典,遍历列表,把列表中每个元素和其索引添加到字典里面

cc = [1, 2, 3, 2, 4]
from collections import defaultdict
dd = defaultdict(list)
for k, va in [(v,i) for i, v in enumerate(cc)]:
    dd[k].append(va)
print(dd)

output:
defaultdict(<class 'list'>, {1: [0], 2: [1, 3], 3: [2], 4: [4]})

  

猜你喜欢

转载自www.cnblogs.com/alex-bn-lee/p/10556354.html