[英]sorted() function in python when reading a file sorts numbers by 1st digit only. I'm trying to print a high scores list in a python game
The code works as long as the numbers don't contain 0's.只要数字不包含 0,代码就可以工作。 Otherwise it sorts like 9 is higher than 10 for example.
否则,它排序为 9 高于 10。
def enter_high_score():
print()
name=input("Please Enter You Name: ")
file=open("score.txt", "a")
file.write(str(9000) +"\t" +(name)+ "\n")
file.close()
file=open("score.txt", "r")
readthefile = file.readlines()
sorted_scores = sorted(readthefile,reverse=True)
print("Top 5 Scores!")
print("Pos\tPoints\tName")
for line in range(5):
# print(str(sortedData[line])+"\t"+str(line+1))
print(str(line+1)+"\t"+str(sorted_scores[line]))
Vahid is right with their answer, but there's no need to seperate that digit out and create a list of tuples to sort based on the first word in the line as an integer. We can just extract that info directly in the call to sorted
. Vahid 的回答是正确的,但是没有必要将该数字分开并创建一个元组列表以根据该行中的第一个单词作为 integer 进行排序。我们可以直接在对
sorted
的调用中提取该信息。
>>> data = """15 hello
... 9 world
... 3 foo bar"""
>>> lines = data.split('\n')
>>> sorted(lines, key=lambda line: int(line.split(' ', 1)[0]))
['3 foo bar', '9 world', '15 hello']
>>>
name = input("Please Enter You Name: ") # note that you are appending to the file and at line 5 writing same score every time file = open("score.txt", "a") # use Python f-string file.write(f"9000\t{name}\n") file.close() file = open("score.txt", "r") lines = file.readlines() # For each line create a list of tuples of (int, str), e.g. [(200,John)] records = list(map(lambda line: (int(line.split()[0]), line.split()[1]), lines)) # Highest first, key is saying sort based on first item in (int, str) which is the score sorted_records = sorted(records, key=lambda r: r[0], reverse=True) print(sorted_records)
I figured out a work around as I'm not quite up to the level as mentioned above.我想出了一个解决方法,因为我还没有达到上面提到的水平。 So basically, I've created some if statements saying that;
所以基本上,我已经创建了一些 if 语句来说明这一点; if number is within a certain range say 999 - 1000 for example add "00" to the front.
如果数字在一定范围内,例如 999 - 1000,请在前面添加“00”。
So my scores read 00100 00010 00001 for example... and if it's over any of those specified values there's an else statement goin "woah you scored off the charts your so good!"例如,我的分数显示为 00100 00010 00001……如果它超过了任何指定的值,就会有一个 else 语句“哇,你的成绩太棒了!”
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.