使用Python随机获取最高价值变量并打印变量名称

2024-04-29 03:33:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我在做一个项目的时候遇到了这个问题,我得到了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 DictionaryPython: finding which variable has the highest value and assign that value to a new variable。 谢谢你的帮助!你知道吗


Tags: andtheis数字名字分数scoreprint
2条回答

您可以根据每个分数创建一个所有获奖者的名单,然后创建一个拥有最高分数的所有指数的名单,然后创建一个所有获奖者的名单。你知道吗

lister = [score1, score2, score3]
list_of_according_winner = ["score1", "score2", "score3"]

# list of highscore indices (if two are equal, you can have several elements)
highscore_index = [i for i, x in enumerate(lister) if x == max(lister)]

# create list of winners
winners = [list_of_according_winner[i] for i in highscore_index]

#printing
print("the highest score is", max(lister), "by", ", ".join(winners))

我省略了“nobody”选项,因为max(lister)总是有一个值,因此总会有一个赢家,至少在实现它时是这样的。你知道吗

您可以使用字典来存储名称和分数,这会将这两位相关数据保存在一起。使用内置的sorted函数首先获得最高分数,比较前两个分数以检查是否有抽屉。你知道吗

from random import randint

l = []

def addTeam(name):
    l.append(
    {"name": name, "score": randint(0, 51)}
    )

def sortScores():
    return sorted(l, key=lambda t: t["score"], reverse=True)

def isDraw():
    if l[0]["score"] == l[1]["score"]:
        return True
    return False

if __name__ == '__main__':
    addTeam("Team1")
    addTeam("Team2")
    addTeam("Team3")
    l = sortScores()

    if isDraw():
        winner = "nobody"
    else:
        winner = l[0]["name"]

    print("The highest score is {} by: {}".format(l[0]["score"], winner))

尽量避免进行*导入,因为这可能会导致冲突。你知道吗

相关问题 更多 >