我在做一个项目的时候遇到了这个问题,我得到了3个随机生成的数字,想要确定最大的数字,然后用它的变量名打印出如下内容:
print("the winner is:", winner, "with", winners_score, "points")
“赢家”是球队的名字,“积分”是球队的积分。我尝试了多种方法来解决这个问题,包括列出一个名单和确定最高分数等,但我不能打印出获奖者的名字,只有获奖者的分数。然后我试了一本字典,名字是键,分数是值,然后反过来。它们都不起作用,然后我尝试了.values()和.keys(),但也不起作用。我最终创建了一段代码来解决这个问题,但是太复杂了,无法在一个有10个以上变量的程序中使用。下面是测试代码:
from random import *
score1 = randint(0, 51)
score2 = randint(0, 51)
score3 = randint(0, 51)
print(score1)
print(score2)
print(score3)
lister = [score1, score2, score3]
highest_score = max(lister)
winner = " "
if score1 > score2 and score1 > score3:
winner = "score1"
elif score2 > score1 and score2 > score3:
winner = "score2"
elif score3 > score1 and score3 > score2:
winner = "score3"
else:
winner = "nobody"
print("the highest score is", highest_score, "by", winner)
但如果我在前两个地方打成平手,这就行不通了。那么,我如何获得最高的分数和赢家与该分数与一个简短的(er)代码行 另外,我也检查了这个网站上的其他问题,但这两个问题都没有给我想要的答案,阅读这些: Finding The Biggest Key In A Python Dictionary 和 Python: finding which variable has the highest value and assign that value to a new variable。 谢谢你的帮助!你知道吗
您可以根据每个分数创建一个所有获奖者的名单,然后创建一个拥有最高分数的所有指数的名单,然后创建一个所有获奖者的名单。你知道吗
我省略了“nobody”选项,因为
max(lister)
总是有一个值,因此总会有一个赢家,至少在实现它时是这样的。你知道吗您可以使用字典来存储名称和分数,这会将这两位相关数据保存在一起。使用内置的
sorted
函数首先获得最高分数,比较前两个分数以检查是否有抽屉。你知道吗尽量避免进行
*
导入,因为这可能会导致冲突。你知道吗相关问题 更多 >
编程相关推荐