我正在尝试找出 list 中所有重复项的列表。
我的代码:
list=['see','eat','feel','see','eat']
i=0
j=0
l=[]
for i in range(len(list)-1):
j=i+1
for j in range(len(list)):
if (list[i]==list[j]):
l.append(list[i])
print(l)
预期输出:
['see', 'eat']
实际输出:
['see', 'see', 'eat', 'eat', 'feel', 'see', 'see']
重复项应该只出现在 list 中。我哪里错了??
请您参考如下方法:
您可以只使用 collections.Counter() 标准库类来获得更高效的方法。
import collections
lst = ['see','eat','feel','see','eat']
lst_counts = collections.Counter(lst)
duplicates = [value for (value, count) in lst_counts.items() if count > 1]
print(duplicates)
输出
['看', '吃']
