6

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

说我有这个词:

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

8 回答 8

17

使用count方法。例如:

(x, mylist.count(x)) for x in set(mylist)
于 2012-08-03T17:49:44.173 回答
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})
于 2012-08-03T18:00:25.673 回答
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
于 2012-08-03T17:53:38.253 回答
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
于 2013-09-29T01:13:32.977 回答
1

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

unique = set(votes)
for item in unique:
    print item
    print votes.count(item)
于 2012-08-03T17:55:36.783 回答
1

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

def tally_votes(l):
  return map(lambda x: (x, len(filter(lambda y: y==x, l))), set(l))
于 2012-08-03T18:14:14.443 回答
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()
于 2020-10-24T22:54:04.453 回答
-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
于 2019-12-17T05:08:10.203 回答