我正在尝试用Python构建它。我的想法是:
我想到了一个清单。当程序询问候选人数时,应使用此编号创建列表。例如:5个候选人,创建list [0,1,2,3,4]
,所以你可以将Candidate1分配给0,Candidate2分配给1,Candidate3分配给2.但是我不知道候选人会有多少,所以我想弄清楚如何自动化这个在一个循环中处理,问你:
list[0,1,2,3,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")
我陷入困境,因为我不知道如何自动化询问候选人名称并将其连接到相应的名单编号的过程。
答案 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]
。