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

时间:2012-08-03 17:47:55

标签: python

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

说我有这个词:

"General Store"

在我的列表中就像是20次。我如何才能发现它在我的列表中出现了20次?我需要知道这一点,所以我可以将该号码显示为"poll vote"答案的类型。

E.g:

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

我将如何以类似于此的方式显示它?:

General Store
20
Mall
50
Ice Cream Van
2

8 个答案:

答案 0 :(得分:15)

使用count方法。例如:

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

答案 1 :(得分: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})

答案 2 :(得分: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

答案 3 :(得分:1)

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

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

答案 4 :(得分:1)

我喜欢这样的问题的单行解决方案:

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

答案 5 :(得分: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

答案 6 :(得分: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()

答案 7 :(得分:-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