Home > other >  sorted() function in python when reading a file sorts numbers by 1st digit only. I'm trying to
sorted() function in python when reading a file sorts numbers by 1st digit only. I'm trying to

Time:12-11

The code works as long as the numbers don't contain 0's. Otherwise it sorts like 9 is higher than 10 for example.

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

    numbers = [5, 6, 90000, 2, 80, 90, 657, 50000]
    butts = sorted(numbers)
    print(butts)```
Ignore the bottom part with sorted numbers = butts. I was just trying to see if the same is true when just sorting from a list instead of an external file. It's not output of "butts"
is [2, 5, 6, 80, 90, 657, 50000, 90000] 

CodePudding user response:

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.

>>> 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']
>>> 

CodePudding user response:

1 name = input("Please Enter You Name: ")
2 # note that you are appending to the file and at line 5 writing same score every time
3 file = open("score.txt", "a")
4 # use Python f-string
5 file.write(f"9000\t{name}\n")
6 file.close()
7 
8 file = open("score.txt", "r")
9 lines = file.readlines()
10 # For each line create a list of tuples of (int, str), e.g. [(200,John)]
11 records = list(map(lambda line: (int(line.split()[0]), line.split()[1]), lines))
12
13 # Highest first, key is saying sort based on first item in (int, str) which is the score
14 sorted_records = sorted(records, key=lambda r: r[0], reverse=True)
15 print(sorted_records)
  • Related