【问题标题】:Looping through dictionaries in a list to find sum of values from matching keys. (Counting Votes)遍历列表中的字典以从匹配键中查找值的总和。 (点票)
【发布时间】:2019-05-01 00:25:01
【问题描述】:

我在柜台上班时遇到了麻烦。我想做的是进行投票计数。键是候选人的名字,值是票数。从用户输入中收集这些信息,并打印出每位候选人的最终票数。

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

对此非常陌生,非常感谢您的帮助。试图在其他帖子中查找解决方案,这就是我发现使用计数器的地方。但在我的代码中不起作用。产生错误:

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

提前谢谢你。

【问题讨论】:

  • 在构建字典时,最好识别输入名称何时与以前的名称相同并将该人的新投票添加到他们的旧投票中,而不是制作一个全新的dict 同名键。

标签: python list loops dictionary


【解决方案1】:

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

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))

【讨论】:

  • 非常感谢!我知道有某种功能可以完成这项工作。我很感激。
  • @TinFoil_Helmet 不用担心。如果有帮助,也可以考虑投票。 :)
【解决方案2】:

使用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))

【讨论】:

    【解决方案3】:

    我认为问题出在b=input('Vote') 行。当你从输入中得到b,它的类型是string,你需要把它改成int,这样数字就可以相加了。加一行代码试试看b=int(b)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多