欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

[python] 查找列表中重复的元素

程序员文章站 2022-07-12 09:27:57
...

已有列表:

a = [1, 2, 3, 2, 1, 5, 6, 5, 5, 5]

写法1:

import collections
print([item for item, count in collections.Counter(a).items() if count > 1])
## [1, 2, 5]

但是 Counter 效率不高,写法2:

seen = set()
uniq = []
for x in a:
    if x not in seen:
        uniq.append(x)
        seen.add(x)

但是上面的code,结果不对,我改成了下面这样:

seen = set()
duplicated = set()
for x in a:  
    if x not in seen:  
        seen.add(x)
    else:
        duplicated.add(x)
print(duplicated)  # {1, 2, 5}

第3种写法比第2种写法更为紧凑,但这种写法不那么直观:

seen = set()
uniq = [x for x in a if x not in seen and not seen.add(x)]  # 这种写法,结果也不对

我自己的写法:

a = [1, 2, 3, 2, 1, 5, 6, 5, 5, 5]
b = set(a)
for each_b in b:
    count = 0
    for each_a in a:
        if each_b == each_a:
            count += 1
    print(each_b, ": ", count)

运行如下:
1 :  2
2 :  2
3 :  1
5 :  4
6 :  1

或者这样写:

a = [1, 2, 3, 2, 1, 5, 6, 5, 5, 5]
duplicated = set()  
for i in range(0, len(a)):
    if a[i] in a[i+1:]:
        duplicated.add(a[i])
print(duplicated)
# {1, 2, 5}

用下面的函数还可以列出重复元素的索引:

a = [1, 2, 3, 2, 1, 5, 6, 5, 5, 5]
source = a
from collections import defaultdict
def list_duplicates(seq):
    tally = defaultdict(list)
    for i,item in enumerate(seq):
        tally[item].append(i)
    return ((key,locs) for key,locs in tally.items() 
                            if len(locs)>1)

for dup in sorted(list_duplicates(source)):
    print(dup)

输出如下:
(1, [0, 4])
(2, [1, 3])
(5, [5, 7, 8, 9])

Index of duplicates items in a python list

如何在一个列表中查找重复的元素并创建新的列表