简体   繁体   English

Python 使用字典和循环声明获胜者

[英]Python declare winner using dictionary and loop

This is the output of the code I am trying to write.这是我尝试编写的代码的输出。 I have seen this done for C++, but not python with a dictionary.我已经看到这是为 C++ 完成的,但不是带有字典的 python。 The key here is the dictionary is not optional.这里的关键是字典不是可选的。 I need to use it to fulfill the assignment.我需要用它来完成任务。

ID  Candidate           Votes Received      % of Total Vote
1   Johnson             5000                55.55
2   Miller              4000                44.44
Total 9000 
and the winner is Johnson!

I need to use a dictionary and a loop to create this.我需要使用字典和循环来创建它。 However, I am stuck on 3 points.但是,我被困在 3 点上。 1.The percent- current code returns the percent before it has the whole total ex: first candidate always has 100%. 1.百分比-当前代码返回百分比之前它有整个总数 ex:第一个候选人总是有 100%。 2. Declare a winner- code finds the max votes and returns the number value but I need it to return the name. 2. 声明一个获胜者-代码找到最大票数并返回数字值,但我需要它来返回名称。 3. How to format the dictionary values so it lines up under the header. 3. 如何格式化字典值,使其在标题下排列。 I don't think is possible, but it must be a requirement to use a dictionary for a reason.我认为这是不可能的,但是出于某种原因必须使用字典。 I am thinking I need to make a copy of the dictionary and format that?我想我需要复制字典并格式化它? Here is what I have so far:这是我到目前为止所拥有的:

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

Which 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
  1. You add the number of each candidates votes at the same time you calculate the percent vote for each candidate.在计算每个候选人的百分比投票的同时,您将每个候选人的票数相加。 You need to find the total votes first, then divide each candidates votes by the total您需要先找到总票数,然后将每个候选人的票数除以总数

  2. You are returning the max of a list of integers.您正在返回整数列表的最大值。 Obviously you aren't going to get a string.显然你不会得到一个字符串。 You need some way to connect the number votes with the candidate.您需要某种方式将票数与候选人联系起来。

  3. Don't bother.不要打扰。 You can try to figure out how many tabs you need to get the whole thing lined up, but from experience, it is basically impossible.您可以尝试计算出需要多少个选项卡才能将整个内容排列起来,但从经验来看,这基本上是不可能的。 You could separate them with commas and open it in excel as a csv, or you could just make the user figure out what number goes with what.您可以用逗号将它们分开,然后在 excel 中将其作为 csv 格式打开,或者您可以让用户弄清楚什么数字与什么数字对应。

The other answer uses data tables, so I will take another, more vanilla and cool approach to getting what you want.另一个答案使用数据表,因此我将采用另一种更原始​​和更酷的方法来获得您想要的东西。

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)

I have added very little changes to your code to make it work:我对您的代码添加了很少的更改以使其正常工作:

I have mentioned the changes as comments in the code.我已经在代码中作为注释提到了这些更改。

Edit: It's more efficient to use objects for each candidate if you require scaling in the future.编辑:如果您将来需要缩放,为每个候选对象使用对象会更有效。

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

I believe that this is the solution you are looking for.我相信这是您正在寻找的解决方案。 Just change the input statements in case you are using Python 2.x.如果您使用的是 Python 2.x,只需更改输入语句。 Using Dataframe, the output will be exactly how you wanted.使用 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])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM