Python 3.x python中列表中的countin投票
我想要一个从列表中统计选票的代码,例如,从这个列表中Python 3.x python中列表中的countin投票,python-3.x,Python 3.x,我想要一个从列表中统计选票的代码,例如,从这个列表中[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:
[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])
将您的
=+
反转为+=
(=+
与普通=
基本相同):
或者更好地使用集合。计数器:
from collections import Counter
counter = Counter(votes)
试试这个:
投票数=['jack'、'jack'、'mat'、'tom'、'tom'、'tom']
>>>计数器={el:投票数。集合(投票数)中el的计数(el)}
>>>柜台
{'tom':3,'mat':1,'jack':2}
from collections import Counter
counter = Counter(votes)