Python list-查找字符串出现的次数

2024-05-23 16:02:55 发布

您现在位置:Python中文网/ 问答频道 /正文

如何查找每个字符串在列表中出现的次数?

说我有话要说:

"General Store"

这在我的单子上大概有20次了。我怎么知道它出现在我的列表中20次?我需要知道这一点,以便可以将该数字显示为"poll vote"答案的类型。

例如:

General Store - voted 20 times
Mall - voted 50 times
Ice Cream Van - voted 2 times

我该如何以类似的方式展示它呢?以下内容:

General Store
20
Mall
50
Ice Cream Van
2

Tags: store字符串列表数字次数van单子general
3条回答

使用count方法。例如:

(x, mylist.count(x)) for x in set(mylist)

举个简单的例子:

   >>> lis=["General Store","General Store","General Store","Mall","Mall","Mall","Mall","Mall","Mall","Ice Cream Van","Ice Cream Van"]
   >>> for x in set(lis):
        print "{0}\n{1}".format(x,lis.count(x))


    Mall
    6
    Ice Cream Van
    2
    General Store
    3

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

相关问题 更多 >