简体   繁体   English

sorted() function in python 在读取文件时仅按第一位数字对数字进行排序。 我正在尝试在 python 游戏中打印高分列表

[英]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.

相关问题 从排序列表python打印唯一数字 - print unique numbers from a sorted list python 尝试从 python 中的排序列表中打印元素 - Trying to print an element from a sorted list in python 我正在尝试将随机数写入文件,然后从 Python 中的行创建一个列表,但列表也需要 '\\n' - I'm trying to write random numbers to a file and then make a list from lines in Python but list takes '\n' too 当我尝试将numpy数组作为第一个参数传递时,poly函数是否仅将列表作为其第一个参数接受,它显示错误 - Does poly function accept only the list as its 1st argument when I tried to pass an numpy array as an 1st argument it is showing an error Python:如何从数字文件(分数)中读取数据以用作列表并获得高分,低分和平均分,并分组为十分位 - Python: How to read from file of numbers (scores) use as list and get high score, low, and average score, and group into deciles 我有一个数字列表,其中第一个数字被附加到一个新列表,然后是最后一个,然后是第二个,然后是第二个数字,依此类推 - I have a list of numbers where the 1st digit is appended to a new list, then last, then 2nd, then 2nd last and so on 我在尝试使用CSV文件和列格式将数字(0-10)读入Python 3的列表时遇到麻烦。 - I'm having trouble trying to read the numbers (0 - 10) into a list in Python 3 using CSV file and in a column format. 我正在尝试如何将此输出打印到 python 上的文本文件 - I'm trying how to print this output to a text file on python Python:创建将高分写入文件的字典 - Python: creating a dictionary that writes high scores to a file 来自外部文件的分数在“前 5 名分数列表”中排序不正确 - Python 游戏 - Scores from an external file not ordering correctly in 'Top 5 scores list' - Python Game
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM