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

6

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

比如说,我有一个单词:

"General Store"

我有一个列表,里面有很多次出现了一个特定的项目。我该如何找出这个项目在列表中出现的次数?我需要知道这个数字,以便将其作为“投票”答案显示。

例如:

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

我该如何以类似于这样的方式显示它?:
General Store
20
Mall
50
Ice Cream Van
2

1
你想它区分大小写吗? - mgilson
我觉得这并不重要,因为我可以先打印字母,然后使用for循环,计算出现次数,并将其放入其中。但是,是的,我希望它们区分大小写。 :) - Aj Entity
8个回答

17
使用count方法。例如:
(x, mylist.count(x)) for x in set(mylist)

7

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

3
为什么不直接使用cnt = Counter(['red','blue','red','green','blue','blue'])呢?现在这样写代码,你可能更好地使用cnt = defaultdict(int),我想这在Python 2.5中提供了一种O(N)的方法来完成此操作(相对于在Python 2.7+中引入Counter)。 - mgilson
我只是从链接的集合文档页面中复制了这个例子,但是Counter([iterable])构造函数确实更加简洁和简单! - dkamins

2

一个简单的例子:

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

1

首先使用set()函数获取列表中的所有唯一元素。然后循环遍历该集合以计算列表中的元素数量。

unique = set(votes)
for item in unique:
    print item
    print votes.count(item)

这似乎是我正在寻找的内容,我了解循环,但我不知道集合函数。我尝试在http://docs.python.org/library/functions.html#func-set上查找,但我仍然不明白我正在设置什么。也许如果您能解释一下投票应该代表什么?我的意思是,我要把“General Store”放在投票中吗?但显然这应该放在“item”中,您可能有理由区分它。 - Aj Entity
1
"votes" 是你想要计数的包含重复字符串的“列表”。而 set() 并不会设置任何东西,它通过删除重复项将列表转换为集合。 - Rajesh J Advani
哦,好的。现在我已经让它工作了,但当我尝试测试它时,使用代码时会出现这样的情况: 谷物产品0 谷物产品0 谷物产品0 谷物产品0 谷物产品0 谷物产品0 谷物产品0 谷物产品0 谷物产品0 谷物产品0 谷物产品0 谷物产品0 谷物产品0 水果和蔬菜0 水果和蔬菜0 水果和蔬菜0 水果和蔬菜0 水果和蔬菜0 水果和蔬菜0 如何让它只是一个单一的类别,在一个地方把所有计数总结起来,以及... - Aj Entity
1
看起来你的代码里还有很多东西没有在这里描述。你有一个包含每个投票字符串的列表/数组对象吗? - Rajesh J Advani
将所有计数累加到一个数字中。如果没有出现0...也许我可以收集并添加所有的1,但其他的都是0,我不知道该怎么办。这是我现在输出的一部分: - Aj Entity
显示剩余4条评论

1

我喜欢像这样的一行代码解决问题:

def tally_votes(l):
  return map(lambda x: (x, len(filter(lambda y: y==x, l))), set(l))

1
我认为 list.count(x)len(filter(...)) 更高效。 - user1479055

1

如果你需要使用字典,建议从一开始就使用字典而不是列表。以下是一个简单的设置:

#list
mylist = ['General Store','Mall','Ice Cream Van','General Store']

#takes values from list and create a dictionary with the list value as a key and
#the number of times it is repeated as their values
def votes(mylist):
d = dict()
for value in mylist:
    if value not in d:
        d[value] = 1
    else:
        d[value] +=1

return d

#prints the keys and their vaules
def print_votes(dic):
    for c in dic:
        print c +' - voted', dic[c], 'times'

#function call
print_votes(votes(mylist))

它的输出结果为:
Mall - voted 1 times
Ice Cream Van - voted 1 times
General Store - voted 2 times

0

如果你愿意使用pandas库,这个方法非常快速:

import pandas as pd 

my_list = lis=["General Store","General Store","General Store","Mall","Mall","Mall","Mall","Mall","Mall","Ice Cream Van"]
pd.Series(my_list).value_counts()

-1
votes=["General Store", "Mall", "General Store","Ice Cream Van","General Store","Ice Cream Van","Ice Cream Van","General Store","Ice Cream Van"]

for vote in set(votes):
    print(vote+" - voted "+str(votes.count(vote))+" times")

试试这个。它会输出

General Store - voted 4 times
Ice Cream Van - voted 4 times
Mall - voted 1 times

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接