我试图建立一个小测验游戏,用户回答一些问题,在游戏结束时,将分配一个十二生肖标志。所以我所做的:
现在我试图获得最高的分数,并显示标志和定义,但我完全被困住了。
以下是问题的一部分:
# THIS IS THE 1ST DICTIONARY
scores = {
"1 Aries": aries,
"2 Taurus": taurus,
"3 Gemini": gemini,
"4 Cancer": cancer,
"5 Leo": leo,
"6 Virgo": virgo,
"7 Libra": libra,
"8 Scorpio": scorpio,
"9 Sagittarius": sagittarius,
"10 Capricorn": capricorn,
"11 Aquarius": aquarius,
"12 Pisces": pisces
}
# THIS IS PART OF THE 2ND DICTIONARY (I won't copy everything here because it's too big)
zsigns_definition = {
"Aries": "You could be Aries: March 21 - April 19. - Aries loves to be number one. Naturally, this dynamic fire sign is no stranger to competition. Aries dives headfirst into even the most challenging situations - and they will make sure they always come out on top! Aries is a passionate, motivated, and confident leader. Aries is easygoing and enjoy the company of all kinds of people.",
"Taurus": "You ....."
}
这是试图匹配分数的代码:
max_score = 0
for key in scores.keys():
if max_score < scores["1 Aries"]:
max_score = scores["1 Aries"]
max_score = key
print(max_score, zsigns_definition["Aries"])
这就是我被困的地方。我真的不知道该怎么做才能找到最高的分数,然后在最后打印出来?我试着为每个星座做这个。
发布于 2021-12-15 14:03:03
我将在假设你的字典scores
实质上等同于这个的情况下回答。
scores = {
"1 Aries": 0,
"2 Taurus": 1,
"3 Gemini": 2,
"4 Cancer": 3,
"5 Leo": 4,
"6 Virgo": 5,
"7 Libra": 6,
"8 Scorpio": 5,
"9 Sagittarius": 4,
"10 Capricorn": 3,
"11 Aquarius": 2,
"12 Pisces": 1
}
如果这是真的,那么要按值获取最大键并从zsigns_definition
打印定义,您可以这样做:
zsigns_definition = {'Libra' : 'Definition of Libra goes here'}
number, sign = max(scores, key=scores.get).split()
print(zsigns_definition[sign])
下面是如何使用for循环做同样的事情:
max_value = 0
max_key = ''
for key, value in scores.items():
if value > max_value:
max_value = value
max_key = key
number, sign = max_key.split()
print(zsigns_definition[sign])
这两项产出都将:
Definition of Libra goes here
我注意到,在您的for循环中,每次发生变化时都会打印最大分数。我认为这只是一个缩进错误,虽然由于语言,“最高的评分和打印it在末尾”。
发布于 2021-12-15 13:30:20
如果我正确理解,分数字典中的值是表示每个符号的玩家分数的数字。
scores = {
"1 Aries": 5,
"2 Taurus": 8,
"3 Gemini": 3
}
zsigns_definition = {
"Aries": "You ...",
"Taurus": "You ...",
"Gemini": "You ..."
}
如果是这样,您可以添加另一个变量来跟踪最大键,并将print语句放在循环之外。
max_key = ""
max_score = 0
for key in scores.keys():
if max_score < scores[key]:
max_score = scores[key]
max_key = key
number, sign = max_key.split() # Split the string on spaces
print(max_score, zsigns_definition[sign]) # prints "8 Taurus"
在这里,max_key.split()按空格分隔文本字符串,并将其放入列表中。因为它总是有两个项目,我们可以通过将两个变量名称放在左边用逗号分隔开来解压。
https://stackoverflow.com/questions/70370412
复制相似问题