我想要一个从列表中计算选票的代码,例如,从这个列表[jack , jack , mat , tom , tom , tom ]
,打印每个候选人的计数:
下面是我尝试过的代码,但不起作用:
votes = ['jack' , 'jack' , 'mat' , 'tom' ,'tom' , 'tom']
counter = dict()
for string in votes :
if string in counter :
counter[string] =+ 1
else:
counter[string] = 1
for this_one in list (counter.keys()) :
print (this_one , counter[this_one])
发布于 2019-09-01 08:17:28
将您的=+
转换为+=
(=+
基本上与普通的=
相同):
counter[string] += 1
或者更好的是,使用collections.Counter
from collections import Counter
counter = Counter(votes)
发布于 2019-09-01 08:18:55
试试这个:
>>> votes = ['jack' , 'jack' , 'mat' , 'tom' ,'tom' , 'tom']
>>> counter = {el: votes.count(el) for el in set(votes)}
>>> counter
{'tom': 3, 'mat': 1, 'jack': 2}
https://stackoverflow.com/questions/57744315
复制