Python列表 - 查找字符串发生的次数

Aj *_*ity 5 python

我怎样才能找到每个字符串出现在我的列表中的次数?

说我有这个词:

"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)


dka*_*ins 6

虽然其他答案(使用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)

  • 为什么不只是`cnt = Counter(['red','blue','red','green','blue','blue'])`` 实际上,您可能也在使用`cnt = defaultdict(int)` - 我想在python 2.5中提供了一种O(N)方式来实现这一点......(与Counter引入时的2.7+相反). ) (3认同)