特定
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']).我怎样才能做到这一点?
>>> [v for v, r in itertools.groupby(sorted(listEx)) if len(list(r)) > 1]
['bird', 'cat']
Run Code Online (Sandbox Code Playgroud)
该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)
| 归档时间: |
|
| 查看次数: |
184 次 |
| 最近记录: |