计票投票计划

时间:2018-01-24 16:56:13

标签: python python-3.x

我正在尝试用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:Jonah [1]
    • 候选人3:Misty [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")

我陷入困境,因为我不知道如何自动化询问候选人名称并将其连接到相应的名单编号的过程。

1 个答案:

答案 0 :(得分:0)

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

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

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