循环遍历列表中的字典,从匹配的键中查找值的总和。(计票)

2024-05-06 08:26:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我很难让柜台工作。我想做的是统计选票。键是候选人的名字,值是票数。从用户输入中收集这些信息,并打印出每个候选人的最终票数。你知道吗

from collections import Counter

name_vote =[]
count = int(input('How many?'))

while count >=1: 
    a=input('Name')
    b=input('Vote')
    c={ a:b }
    name_vote.append(c)
    count = count - 1

print(name_vote)

c = Counter()
for d in name_vote:
    c.update(d)

print(c)

用户首先告诉有多少投票输入(这是计数)

输入如下: 有多少?=6个

约翰2

清单5

约翰4

斯科特11

约翰3

斯科特1

结果:(打印出来)

约翰9

清单5

斯科特12

非常新,非常感谢你的帮助。尝试在其他帖子中查找解决方案,这就是我发现使用counter的地方。但在我的代码中不起作用。产生错误:

Traceback (most recent call last):
  File "c:/Users/Rghol5212/hello/Dico.py", line 30, in <module>
    c.update(d)
  File "C:\Users\Rghol5212\AppData\Local\Programs\Python\Python37- 
 32\lib\collections\__init__.py", line 649, in update
    self[elem] = count + self_get(elem, 0)
TypeError: can only concatenate str (not "int") to str

先谢谢你。你知道吗


Tags: 用户nameininputcountcounterupdateusers
3条回答

我想问题出在b=input('Vote')行。当您从输入中获取b时,它的类型是string,您需要将其更改为int,这样就可以添加数字了。尝试添加一行代码b=int(b)。你知道吗

尝试改用defaultdict。如果字典中不存在该名称,将使用默认值0。如果名字存在,投票只会增加计数。你知道吗

from collections import defaultdict

name_vote = defaultdict(int)

count = int(input('How many?'))

while count >=1: 
    a=input('Name')
    b=input('Vote')
    name_vote[a] = name_vote[a] + int(b)
    count = count - 1

for k,v in name_vote.items():
    print("{} {}".format(k,v))

使用Counter

from collections import Counter

name_vote = Counter()

count = int(input('How many? '))

while count >= 1:
    name = input('Name ')
    vote = int(input('Vote '))
    name_vote += {name: vote}
    count -= 1

for name, cnt in name_vote.items():
    print("Name: {}, Vote: {}".format(name, cnt))

相关问题 更多 >