我试图修改此列表中重复项目的定义,以便列出重复值的索引。另外,我希望列出所有重复项,这意味着a = [1,2,3,2,1,5,6,5,5,5]的结果将为duplicate_indexes = [3,4,7 ,8,9]这里的定义是:使用Python列出列表中重复值的索引
def list_duplicates(seq):
seen = set()
seen_add = seen.add
# adds all elements it doesn't know yet to seen and all other to seen_twice
seen_twice = set(x for x in seq if x in seen or seen_add(x))
# turn the set into a list (as requested)
return list(seen_twice)
a = [1,2,3,2,1,5,6,5,5,5]
list_duplicates(a) # yields [1, 2, 5]
您正在使用一组'''seen'''使成员资格测试快速? – wwii
@wwii是的。与其他答案相比,您是正确的 – thefourtheye