简体   繁体   English

计算用作字典值的列表中的项目

[英]Counting items in a List used as a Dictionary Value

I have the following dictionary of lists working fine, but the printing at the end is borked, I can't get the counter to return correct numbers of items in each list as soon as I get more than one key in my dictionary! 我有以下列表的字典可以正常工作,但是最后的打印很糟糕,一旦字典中有多个键,我就无法获得计数器来返回每个列表中正确数量的项目! It's supposed to tell me how many people have chosen a particular dessert as their favourite. 它应该告诉我有多少人选择了特定的甜点作为他们的最爱。

desserts = {}

name_vote = input ('Name:vote ')

while name_vote != '':
  no_colon_name_vote = name_vote.replace(":", " ")
  listed_name_vote = no_colon_name_vote.split()
  name = listed_name_vote[0] 
  vote = ' '.join(listed_name_vote[1:])
  if vote not in desserts:
    desserts[vote] = [name]
  else:
    desserts[vote].append(name)
  name_vote = input ('Name:vote ')

for dessert in desserts:
  count = sum(len(entries) for entries in desserts.values())
  print(dessert, count,'vote(s):',' '.join(desserts[dessert]))

Desired output: 所需的输出:

apple pie 1 vote(s): Georgina
gelato 2 vote(s): Sophia Kirsten
chocolate 3 vote(s): Greg Will James

But instead I get all three values set to 6! 但是,我将所有三个值都设置为6!

Here's a simpler version which should work ok: 这是一个更简单的版本,应该可以正常运行:

from collections import defaultdict

desserts = defaultdict(list)

while True:
    name_vote = input('Name:vote ')
    if name_vote == '':
        break
    name, vote = name_vote.split(':')
    desserts[vote].append(name)

for dessert, names in desserts.items():
    print(dessert, len(names), 'vote(s):', ' '.join(names))

Note the simpler string splitting code, and also how doing the while loop like this means you can avoid having to repeat the line of setup code. 请注意更简单的字符串拆分代码,以及执行此类 while循环的方式,这意味着您可以避免重复安装代码行。 Also, using a defaultdict and iterating over the dict items() also simplify the code a bit 另外,使用defaultdict并遍历dict items()也可以简化代码。

count is based on the sum over the entire desserts list, not desserts[dessert] . count是基于整个desserts列表中的sum ,而不是desserts[dessert]

Try this: 尝试这个:

count = len(desserts[dessert])

Also consider using defaultdict . 还可以考虑使用defaultdict


Let's take a step back and try this instead: 让我们退后一步,尝试以下操作:

desserts = collections.defaultdict(list)
while name_vote != '':
    name_vote = input('Name:vote ')
    if not name_vote:
        break
    name, vote = no_colon_name_vote.split(':')
    desserts[vote].append(name)

for dessert in desserts:
    count = len(desserts[dessert])
    print(dessert, count,'vote(s):',' '.join(desserts[dessert]))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM