Python 使用字典和循环声明获胜者
Python declare winner using dictionary and loop
这是我正在尝试编写的代码的输出。我已经看到这是为 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.The percent- 当前代码 returns 在它拥有整个总数之前的百分比 ex:第一个候选人总是有 100%。
2. 宣布获胜者代码找到最大票数和 return 数值,但我需要它 return 名称。
3. 如何格式化字典值使其在 header 下排列。我不认为这是可能的,但它必须是出于某种原因使用字典的要求。我在想我需要复制字典并格式化吗?
这是我目前所拥有的:
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))
哪个 returns:
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
我相信这就是您正在寻找的解决方案。如果您使用 Python 2.x,只需更改输入语句即可。使用 Dataframe,输出将完全符合您的要求。
import pandas as pd
import numpy as np
df = pd.DataFrame(columns=["Candidate", "Votes Received","Percentage of total votes"])
names=list()
votes=list()
while True:
name = str(input("Enter Name of Candidate."))
if name=='':
break
else:
vote = int(input("Enter the number of votes obtained."))
names.append(name)
votes.append(vote)
s=sum(votes)
xx=(votes.index(max(votes)))
myArray = np.array(votes)
percent = myArray/s*100
for i in range(len(names)):
df1 = pd.DataFrame(data=[[names[i],votes[i],percent[i]]],columns=["Candidate", "Votes Received","Percentage of total votes"])
df = pd.concat([df,df1], axis=0)
df.index = range(len(df.index))
print (df)
print ("Total votes = ",s)
print ("The man who won is ",names[xx])
您在计算每个候选人的百分比选票的同时添加每个候选人的票数。您需要先找到总票数,然后将每个候选人的票数除以总票数
您正在返回整数列表的最大值。显然你不会得到一个字符串。您需要一些方法将票数与候选人联系起来。
不客气。您可以尝试弄清楚需要多少个选项卡才能将整个内容排成一行,但根据经验,这基本上是不可能的。您可以用逗号分隔它们并将其作为 csv 在 excel 中打开,或者您可以让用户弄清楚什么数字对应什么。
另一个答案使用数据表,所以我将采用另一种更普通、更酷的方法来获得您想要的内容。
class candidate():
def __init__(self, name, votes):
self.name = name
self.votes = int(votes)
def percentvotes(self, total):
self.percent = self.votes/total
def printself(self, i):
print('{}\t{}\t\t{}\t\t{}'.format(i, self.name, self.votes, self.percent))
def getinput():
inp = input('Please enter your candidates name and votes')
return inp
candidates = []
inp = getinput()
s = 0
while inp != '':
s+=1
candidates.append(candidate(*inp.split(" ")))
inp = getinput()
for c in candidates:
c.percentvotes(s)
candidates.sort(key = lambda x:-x.percent)
print('ID\tname\t\tvotes\t\tpercentage')
for i, c in enumerate(candidates):
c.printself(i+1)
我对您的代码进行了很少的更改以使其正常工作:
我已经在代码中以注释的形式提到了更改。
编辑:如果您将来需要扩展,为每个候选人使用对象会更有效。
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)
# I change it to a list so it's much easier to append to it later
dct[i] = list((name,int(votes)))
i += 1
# I calculate the total percent of votes in the end and append to the candidate
maxVal = 0
for i in range(1, len(dct) + 1):
if dct[i][1] > maxVal:
maxInd = i
dct[i].append(int((dct[i][len(dct[i]) - 1]) / total * 100))
header='{:>0}{:>10}{:>10}{:>20}'.format('ID','Name','Votes','% of Total Vote')
print(dct)
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 '+ dct[maxInd][0]))
这是我正在尝试编写的代码的输出。我已经看到这是为 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.The percent- 当前代码 returns 在它拥有整个总数之前的百分比 ex:第一个候选人总是有 100%。 2. 宣布获胜者代码找到最大票数和 return 数值,但我需要它 return 名称。 3. 如何格式化字典值使其在 header 下排列。我不认为这是可能的,但它必须是出于某种原因使用字典的要求。我在想我需要复制字典并格式化吗? 这是我目前所拥有的:
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))
哪个 returns:
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
我相信这就是您正在寻找的解决方案。如果您使用 Python 2.x,只需更改输入语句即可。使用 Dataframe,输出将完全符合您的要求。
import pandas as pd
import numpy as np
df = pd.DataFrame(columns=["Candidate", "Votes Received","Percentage of total votes"])
names=list()
votes=list()
while True:
name = str(input("Enter Name of Candidate."))
if name=='':
break
else:
vote = int(input("Enter the number of votes obtained."))
names.append(name)
votes.append(vote)
s=sum(votes)
xx=(votes.index(max(votes)))
myArray = np.array(votes)
percent = myArray/s*100
for i in range(len(names)):
df1 = pd.DataFrame(data=[[names[i],votes[i],percent[i]]],columns=["Candidate", "Votes Received","Percentage of total votes"])
df = pd.concat([df,df1], axis=0)
df.index = range(len(df.index))
print (df)
print ("Total votes = ",s)
print ("The man who won is ",names[xx])
您在计算每个候选人的百分比选票的同时添加每个候选人的票数。您需要先找到总票数,然后将每个候选人的票数除以总票数
您正在返回整数列表的最大值。显然你不会得到一个字符串。您需要一些方法将票数与候选人联系起来。
不客气。您可以尝试弄清楚需要多少个选项卡才能将整个内容排成一行,但根据经验,这基本上是不可能的。您可以用逗号分隔它们并将其作为 csv 在 excel 中打开,或者您可以让用户弄清楚什么数字对应什么。
另一个答案使用数据表,所以我将采用另一种更普通、更酷的方法来获得您想要的内容。
class candidate():
def __init__(self, name, votes):
self.name = name
self.votes = int(votes)
def percentvotes(self, total):
self.percent = self.votes/total
def printself(self, i):
print('{}\t{}\t\t{}\t\t{}'.format(i, self.name, self.votes, self.percent))
def getinput():
inp = input('Please enter your candidates name and votes')
return inp
candidates = []
inp = getinput()
s = 0
while inp != '':
s+=1
candidates.append(candidate(*inp.split(" ")))
inp = getinput()
for c in candidates:
c.percentvotes(s)
candidates.sort(key = lambda x:-x.percent)
print('ID\tname\t\tvotes\t\tpercentage')
for i, c in enumerate(candidates):
c.printself(i+1)
我对您的代码进行了很少的更改以使其正常工作:
我已经在代码中以注释的形式提到了更改。
编辑:如果您将来需要扩展,为每个候选人使用对象会更有效。
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)
# I change it to a list so it's much easier to append to it later
dct[i] = list((name,int(votes)))
i += 1
# I calculate the total percent of votes in the end and append to the candidate
maxVal = 0
for i in range(1, len(dct) + 1):
if dct[i][1] > maxVal:
maxInd = i
dct[i].append(int((dct[i][len(dct[i]) - 1]) / total * 100))
header='{:>0}{:>10}{:>10}{:>20}'.format('ID','Name','Votes','% of Total Vote')
print(dct)
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 '+ dct[maxInd][0]))