【问题标题】:Finding the key of the max value in a dictionary在字典中查找最大值的键
【发布时间】:2014-09-26 03:32:37
【问题描述】:

基本上我有这个代码,我需要一个特定的输出,我在其中说明获胜者和他的票数。我似乎已经找到了最大值,但不是它的关键对应物。错误出现在我的倒数第二个输出中。让我知道你们的想法,这可能很容易解决,谢谢!!!

print()
print()
print()
import sys
fo = open(sys.argv[1], "r")
dic = {}
count = 0
winner = 0

print("Candidates".center(15), "Votes".rjust(10), "Percent".rjust(10))
print("==========".center(15), "=====".rjust(10), "=======".rjust(10))

for line in fo:
    line = line[:-1]
    x = line.split(" ")
    names = (x[0]) + " " + (x[1])
    votes = int(x[2]) + int(x[3]) + int(x[4]) + int(x[5])
    dic[names] = votes
    count = votes + count
    if winner < votes:
        winner = votes

for i in dic.keys():
    percent = int((dic[i]/count)*100.00)
    print (i.center(15),str(dic[i]).center(15),str(percent)+"%")

#Loop through every kid and find percentage, 
print()
print("The winner is", "" , "with", winner, "votes!")
print()
print("Total votes polled:", count)
print()
print()
print()

【问题讨论】:

  • 既然你只是在寻找胜利者,你为什么要把其他人都存储在字典里呢?只需跟踪获胜者的姓名和他们在两个变量中获得的分数,然后最后简单地打印这些。要打印号码,请执行此操作str(winner)
  • 呃。好的。这就说得通了。所以,如果获胜者
  • 我必须循环,因为我需要输出每个人的百分比和投票。明白了:如果获胜者
  • 要跟踪名称,只需声明一个将保存名称的变量。当您获得获胜者的新最高分数时,还将 name 变量更新为具有该分数的人的姓名

标签: python-3.x dictionary output


【解决方案1】:
import operator
dic = {'a':1000, 'b':3000, 'c': 100}
max(dic.items(), key=operator.itemgetter(1))[0]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-18
    • 1970-01-01
    • 1970-01-01
    • 2012-09-14
    • 2014-10-06
    相关资源
    最近更新 更多