【发布时间】:2018-07-29 01:39:05
【问题描述】:
这是我正在尝试编写的代码的输出。我已经看到这是为 C++ 完成的,但不是带有字典的 python。这里的关键是字典不是可选的。我需要用它来完成任务。
ID Candidate Votes Received % of Total Vote
1 Johnson 5000 55.55
2 Miller 4000 44.44
Total 9000
and the winner is Johnson!
我需要使用字典和循环来创建它。但是,我被困在 3 点上。 1.percent-current 代码在获得全部总数之前返回百分比 ex:第一个候选人总是有 100%。 2. 声明一个获胜者 - 代码找到最大票数并返回数字值,但我需要它来返回名称。 3. 如何格式化字典值,使其在标题下对齐。我认为不可能,但是出于某种原因必须要求使用字典。我在想我需要复制字典并格式化吗? 这是我目前所拥有的:
totalVotes=[]
dct = {}
i = 1
while(True):
name = input('Please enter a name: ')
if name == '':
break
votes = input('Please enter vote total for canidate: ')
totalVotes.append(votes)
totalVotesInt= map(int, totalVotes)
total = sum(totalVotesInt)
dct[i] = {name,votes,int(votes)/total*100}
i += 1
header='{:>0}{:>10}{:>10}{:>20}'.format('ID','Name','Votes','% of Total Vote')
print(header)
print("\n".join("{}\t{}".format(key, value) for key, value in dct.items()))
print('Total '+str(total))
print('The Winner of the Election is '+max(totalVotes))
返回:
Please enter a name: Smith
Please enter vote total for canidate: 100
Please enter a name: Frieda
Please enter vote total for canidate: 200
Please enter a name: West
Please enter vote total for canidate: 10
Please enter a name:
ID Name Votes % of Total Vote
1 {'Smith', '100', 100.0}
2 {'Frieda', 66.66666666666666, '200'}
3 {3.225806451612903, '10', 'West'}
Total 310
The Winner of the Election is 200
【问题讨论】:
-
检查我写的代码。 PS-它是用 Python 3 编写的。
标签: python loops dictionary vote