[英]How do I sort a list if there is an integer tied to a string by the smallest number?
I am quite new to programming and I am trying to make a leader board for a number guessing game in python 3 where you have the score then the name sorted by the lowest score first: 我对编程很陌生,我正在尝试在python 3中为数字猜谜游戏制作一个排行榜,在那里你有得分,然后名字按照最低得分排序:
leaderboard_list = [0,0,0,0,0]
while True:
leaderboard_list.sort()
print("This in the leaderboard",leaderboard_list)
name = ("What is your name?")
while user_num != answer:
user_num = input("Guess a number: ")
if user_num = answer:
print("YAY")
else:
score = score + 1
leaderboard_list.append(score+" "+name)
I have tried many different ways and have figured out that if you get a score of 11, then it will say you are higher in the leader board than someone with a score of 2, which it shouldn't. 我已经尝试了很多不同的方法并且已经发现,如果你得到11分,那么它会说你在领导板上的得分高于得分为2的人,这不应该。 I have also tried to change the score to an int type however you can't have an int and a string in the same list. 我还尝试将分数更改为int类型,但是在同一列表中不能有int和字符串。 How can I get around this? 我怎么能绕过这个?
The leaderboard itself should store more structured data; 排行榜本身应存储更多结构化数据; use strings only to display the data. 仅使用字符串来显示数据。
# Store a list of (name, score) tuples
leaderboard = []
while True:
# Print the leaderboard
print("This in the leaderboard")
for name, score in leaderboard:
print("{} {}".format(score, name))
name = ("What is your name?")
score = 0
while user_num != answer:
user_num = input("Guess a number: ")
if user_num == answer:
print("YAY")
else:
score = score + 1
# Store a new score
leaderboard.append((name, score))
# Sort it
leaderboard = sorted(leaderboard, key=lambda x: x[1], reverse=True)
# Optional: discard all but the top 5 scores
leaderboard = leaderboard[:5]
Note that there are better ways to maintain a sorted list than to resort the entire leaderboard after adding a new score to the end, but that's beyond the scope of this answer. 请注意,维护排序列表的方法比在最后添加新分数后使用整个排行榜更好,但这超出了此答案的范围。
dictionaries are well suited for the task of storing the scores and linking them to the user name. 字典非常适合存储分数并将它们链接到用户名的任务。 Dictionaries can't be directly sorted. 字典无法直接排序。 However, there is an easy solution in this other post . 但是,在这篇文章中有一个简单的解决方案。
Moreover, in the OP, the name declaration is wrong, as it is not getting any value from the user. 而且,在OP中,名称声明是错误的,因为它没有从用户获得任何值。 With the following code, it works perfectly. 使用以下代码,它完美地工作。 A condition for ending the while
loop should added as well. 还应添加结束while
循环的条件。
import operator
#Store the names and scores in a dictionary
leaderboard_dict = {}
#Random number
answer = 3
while True:
#Sort the dictionary elements by value
sorted_x = sorted(leaderboard_dict.items(), key=operator.itemgetter(1))
#Rewrite the leaderboard_dict
leaderboard_dict = dict(sorted_x)
print("This in the leaderboard",leaderboard_dict)
name = input("What is your name?")
#initialize score and user_num for avois crashes
user_num = -1
score = 0
while user_num != answer:
user_num = input("Guess a number: ")
if user_num is answer:
print("YAY")
else:
score += 1
leaderboard_dict[name] = score
EDIT: In case that you want to store more than one score for each player, I would user NumPy arrays , as they let you do plenty of operations, like ordering indexes by slicing and getting their numeric order, that is the request of the OP. 编辑:如果你想为每个玩家存储多个分数,我会使用NumPy数组 ,因为它们可以让你做大量的操作,比如通过切片和获取数字顺序来排序索引,这就是OP的请求。 Besides, their syntax is very understandable and Pythonic: 此外,他们的语法是非常容易理解的和Pythonic:
import numpy as np
#Random number
answer = 3
ranking = np.array([])
while True:
name = input("What is your name?")
user_num = -1
score = 1
while user_num != answer:
user_num = input("Guess a number: ")
if user_num is answer:
print("YAY")
else:
score += 1
#The first iteration the array is created
if not len(ranking):
ranking = np.array([name, score])
else:
ranking = np.vstack((ranking, [name,score]))
#Get the index order of the scores
order = np.argsort(ranking[:,1])
#Apply the obtained order to the ranking array
ranking = ranking[order]
And an example of its use: 以及它的一个使用示例:
>> run game.py
What is your name?'Sandra'
Guess a number: 3
YAY
What is your name?'Paul'
Guess a number: 6
Guess a number: 3
YAY
What is your name?'Sarah'
Guess a number: 1
Guess a number: 5
Guess a number: 78
Guess a number: 6
Guess a number: 3
YAY
What is your name?'Sandra'
Guess a number: 2
Guess a number: 4
Guess a number: 3
YAY
What is your name?'Paul'
Guess a number: 1
Guess a number: 3
YAY
Being the output: 作为输出:
print ranking
[['Sandra' '1']
['Paul' '2']
['Paul' '2']
['Sandra' '3']
['Sarah' '5']]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.