【问题标题】:Counting the votes of items listed in an array_ python计算数组python中列出的项目的票数
【发布时间】:2021-08-16 05:02:52
【问题描述】:

有一个聚会,每个人都必须写下他们想要的水果,这样做他们也是在投票。之后应该打印水果和票数(出现的次数)。

示例输入

输入各方名称(以 DONE 结尾):

苹果

橙子

橙子

橙子

香蕉

香蕉

猕猴桃

橙子

苹果

橙子

完成


样本输出

票数:

苹果 - 2

香蕉 - 2

猕猴桃 - 1

橙子 - 5

梨 - 1

a = []
print("Enter the names of parties (terminated by DONE):")
item = input()
while not item == "DONE" : 
    if item not in a: 
        a.append(item)
    item = input()
a = sorted(a)
print()
print("Vote counts:")
for i in a:
    print(i,"-",counts) 

【问题讨论】:

  • 你有什么问题?
  • 我用哪个函数来计数?
  • from collections import Counter,然后Counter(a) 将为您提供所需的结果,尽管格式略有不同。
  • Python 是区分大小写的语言
  • @Dj_Casoko - 它只打印一个,因为您不允许多次添加项目,因为您使用行 if item not in a: 过滤掉这些条目

标签: python arrays python-3.x list while-loop


【解决方案1】:

你不能import Counter,因为你用小写的“C”写了“counter”。

在您的代码中,使用这一行

if item not in a: 
    a.append(item)

您只是将不存在的列表项添加到列表中,因此您将获得 1 的最大计数。 也许这就是你要找的东西:

from collections import Counter
fruit_list = []
item = ""
while True:
    item = input("Enter the names of parties (terminated by DONE): ")
    if item == "DONE":
        break
    else:
        print("You have chosen: {}".format(item))
        fruit_list.append(item)
        my_count = Counter(fruit_list)

for key,value in my_count.items():
    print("\n{:<10} has been chosen {:<2}{:<2} times.".format(key,"",value))

【讨论】:

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