简体   繁体   English

确定最高价值的变量并使用python random打印变量的名称

[英]determining the highest worth variable and printing the variable's name using python random

I've got this problem while i was making a project where i got 3 random generated numbers and want to determine the highest number and then using it's variable name and print out something like this: 我在制作一个有3个随机生成的数字并想确定最高数字然后使用它的变量名并打印出类似以下内容的项目时遇到了这个问题:

print("the winner is:", winner, "with", winners_score, "points")

the "winner" is the teams name and the "points is the amount of points it had. I tried multiple ways to solve this problem including making a list and determining the highest score, etc. But i couldn't print the winner's name, only the winner's score. I then tried a dictionary with the name as key and the score as value and then the other way around. They both didn't work, i then tried .values() and .keys() but also didn't work. I finally created a piece of code to solve it but was too complex to use in a program with more than 10 variables. Here's the code of that test: “获胜者”是球队的名称,“积分是它拥有的积分的数量。我尝试了多种方法来解决此问题,包括列出列表并确定最高得分等。但是我无法打印出获胜者的姓名,我只尝试了赢家的分数。然后我尝试了一个字典,名称是键,分数是值,反之亦然。它们都没有用,然后我尝试了.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)

but this wouldn't work if i has a draw between the first two places. 但是,如果我在前两个地方之间平局,这将行不通。 So how do i get the highest score and the winner with that score with a short(er) line of code PS. 因此,如何用短代码PS来获得最高分数和获胜者。 I have also checked other questions on this website but both questions didn't give me the wanted answer, to read those: Finding The Biggest Key In A Python Dictionary and Python: finding which variable has the highest value and assign that value to a new variable . 我还检查了该网站上的其他问题,但是两个问题都没有给我想要的答案,请阅读以下内容: 在Python词典Python中找到 最大的键 :查找哪个变量具有最高的值并将该值分配给新的可变的 thank you for your help! 谢谢您的帮助!

You can create a list of all according winner names to each score, then create list of all indices with the highest score and then create a list of all winners. 您可以创建每个得分的所有获奖者姓名的列表,然后创建得分最高的所有索引的列表,然后创建所有获奖者的列表。

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

I omitted the option "nobody", as max(lister) will always have a value and therefore there will be always a winner, at least in the way as you implemented it. 我省略了选项“ nobody”,因为max(lister)总是有一个值,因此,至少在实现它的方式上,总会有赢家。

You can use a dictionary to store the name and score, this keeps those two bits of associated data together. 您可以使用字典来存储名称和分数,这会将关联数据的这两部分保持在一起。 Use the built-in sorted function to get the highest score first, comparing the first two scores to check if there was a drawer. 使用内置的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))

Try to avoid doing * imports, as this can lead to conflicts. 尽量避免执行*导入操作,因为这可能导致冲突。

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

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