计数投票程序

2024-05-12 21:10:16 发布

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

我正在尝试用Python构建它。我的想法是:

  • 程序启动
  • 询问有多少候选人和他们的名字
  • 不断地问“你想给谁投票?”在
  • 投票结束后,只需写上“完成”,程序就会打印结果

问题:

  • 我想到了一个单子。当程序询问你候选人的数量时,应该用这个数字创建一个列表。例如:5个候选,创建list [0,1,2,3,4],这样您就可以将Candidate1分配给0,Candidate2分配给1,Candidate3分配给2。但我不知道有多少候选人,所以我想弄清楚如何在一种循环中自动执行这个过程,这个循环会问你:

    • 有多少候选人?5个?完美,创建了一个list[0,1,2,3,4]
    • 插入候选人姓名:
    • 候选人1:Albert[0]
    • 候选人2:约拿[1]
    • 候选人3:米斯蒂[2]
    • 候选人4:唐纳德[3]
    • 候选人5:玛丽[4]

然后让你分配投票,当你写“完成”时,程序会计算并给出结果。在

有什么想法吗?希望我说得对。谢谢。为糟糕的英语道歉。在

编辑:

好吧,我想我不太清楚。在

candidates = input("How many candidates do we have?\n")
candidates = int(candidates)
print("OK! So we have " + str(candidates) + " votable candidates.")
print("Specify their names!\n")


for candidates_number in range(candidates): 
    print(int(candidates_number)) '''to help me visualize what i'm doing'''


overall = candidates
print(list(range(overall)))
complete_list = range(overall)
print(complete_list) '''to help me visualize what i'm doing'''

for candidate_name in range(complete_list):
    print("Write candidates names.\n")

在这里我陷入了困境,因为我不知道如何自动地询问候选人姓名并将其与列表中相应的号码连接起来。在


Tags: 程序列表nameshaverange投票listint
1条回答
网友
1楼 · 发布于 2024-05-12 21:10:16

如果我对你的理解是对的,这就是你需要的:

total_candidates = int(input("How many candidates do we have?\n"))
print("OK! So we have {0} votable candidates.".format(total_candidates))
print("Specify their names!")

candidates = []

for candidate_number in range(total_candidates):
    print('Candidate {0}:'.format(candidate_number + 1))
    name = input('Whats the name of this candidate?\n')
    candidate_info = (candidate_number + 1, name)
    candidates.append(candidate_info)

print(candidates)

将输出:

How many candidates do we have? 
3 OK! So we have 3 votable candidates.
Specify their names! 
Candidate 1: Whats the name of this candidate? 
Albert 
Candidate 2: Whats the name of this candidate? 
John 
Candidate 3: Whats the name of this candidate?
Peter 
[(1, 'Albert'), (2, 'John'), (3, 'Peter')]

结果是tupleslist。只需通过索引访问它的每个元素。例如,如果您想要名称,只需在迭代时执行candidate[1]。在

相关问题 更多 >