Python计算项目在列表中的外观

pha*_*s15 0 python

特定

listEx = ['cat', 'dog', 'cat', 'turtle', 'apple', 'bird', 'bird']

for i in listEx:
    if listEx.count(i) > 1:
        print "this item appears more than once", i
    else:
        print "this item appears only once", i
Run Code Online (Sandbox Code Playgroud)

我希望它打印出猫和鸟出现不止一次(或只是生产['cat', 'bird']).我怎样才能做到这一点?

Ign*_*ams 5

>>> [v for v, r in itertools.groupby(sorted(listEx)) if len(list(r)) > 1]
['bird', 'cat']
Run Code Online (Sandbox Code Playgroud)


Ray*_*ger 5

collections.Counter工具让这类任务非常简单:

>>> from collections import Counter
>>> listEx = ['cat', 'dog', 'cat', 'turtle', 'apple', 'bird', 'bird']
>>> [k for k, cnt in Counter(listEx).items() if cnt > 1]
['bird', 'cat']
Run Code Online (Sandbox Code Playgroud)