Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x python中列表中的countin投票_Python 3.x - Fatal编程技术网

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)