我怎样才能找到每个字符串出现在我的列表中的次数?
说我有这个词:
"General Store"
Run Code Online (Sandbox Code Playgroud)
这在我的列表中就像20次.我如何才能发现它在我的列表中出现了20次?我需要知道这一点,所以我可以将这个数字显示为一种"poll vote"答案.
例如:
General Store - voted 20 times
Mall - voted 50 times
Ice Cream Van - voted 2 times
Run Code Online (Sandbox Code Playgroud)
我将如何以类似于此的方式显示它?:
General Store
20
Mall
50
Ice Cream Van
2
Run Code Online (Sandbox Code Playgroud)
小智 15
使用该count方法.例如:
(x, mylist.count(x)) for x in set(mylist)
Run Code Online (Sandbox Code Playgroud)
虽然其他答案(使用list.count)确实有效,但它们在大型列表上可能会非常慢.
考虑使用collections.Counter,如http://docs.python.org/library/collections.html中所述
例:
>>> # Tally occurrences of words in a list
>>> cnt = Counter()
>>> for word in ['red', 'blue', 'red', 'green', 'blue', 'blue']:
... cnt[word] += 1
>>> cnt
Counter({'blue': 3, 'red': 2, 'green': 1})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
20964 次 |
| 最近记录: |