计算数组中列出的项目的投票数

2024-03-28 10:11:55 发布

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

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

样本输入

输入各方名称(以“完成”终止):

苹果

橙子

橙子

橙子

香蕉

香蕉

猕猴桃

橙子

苹果

橙子

完成


样本输出

计票:

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

Tags: in苹果inputnot投票item样本print
1条回答
网友
1楼 · 发布于 2024-03-28 10:11:55

您不能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))

相关问题 更多 >