如何在列表中找到重复项并用它们创建另一个列表?有答案
How to find the duplicates in a list and create another list with them ? with answer
我自己的解决方案:
list1=[1,2,3,4,4,5,5,5,6,6,7,8,8,8,8]
counter=0
for j in list(set(list1)):
for i in list1:
if j==i:
counter=counter+1
print(j,"have",counter,"duplicates")
counter=0
提点建议
使用collections.Counter
:
>>> list1 = [1,2,3,4,4,5,5,5,6,6,7,8,8,8,8]
>>> from collections import Counter
>>> [(i, count) for i, count in Counter(list1).items() if count > 1]
[(4, 2), (5, 3), (6, 2), (8, 4)]
我自己的解决方案:
list1=[1,2,3,4,4,5,5,5,6,6,7,8,8,8,8]
counter=0
for j in list(set(list1)):
for i in list1:
if j==i:
counter=counter+1
print(j,"have",counter,"duplicates")
counter=0
提点建议
使用collections.Counter
:
>>> list1 = [1,2,3,4,4,5,5,5,6,6,7,8,8,8,8]
>>> from collections import Counter
>>> [(i, count) for i, count in Counter(list1).items() if count > 1]
[(4, 2), (5, 3), (6, 2), (8, 4)]