python算法,在列表中查找重复项

时间:2014-01-02 11:16:29

标签: python algorithm

我需要在python列表中找到所有唯一值,如果有重复写入其中有多少,例如:

['apple','cherry','coffee','apple','coffee','coffee']

,输出应为:

apple 2
cherry 1
coffee 3

2 个答案:

答案 0 :(得分:2)

>>> from collections import Counter
>>> Counter(['apple','cherry','coffee','apple','coffee','coffee'])
Counter({'coffee': 3, 'apple': 2, 'cherry': 1})
>>> for k,v in _.items():
...   print k,v
... 
cherry 1
coffee 3
apple 2

答案 1 :(得分:1)

看起来像是作业......这是一个直接的方法:

lst = ['apple','cherry','coffee','apple','coffee','coffee']

res = {}
for obj in lst:
    if obj not in res:
        res[obj] = 0
    res[obj] += 1

print res