简体   繁体   中英

Python: Sorting Tuples in array based off first element

I had a file with records ( highscores ) stored as an int on each line (with a header).

In my python project I was reading the records into an array, then adding a record (just an int ), sorting the array (with the new record added) and then overwriting the file with the new records (and header - which remained the same)

Here is the relevant code I used for that:

highscores = []
with open("highscore.txt", "r") as f:
    f.readline() # Reads header
    for line in f:
        highscores.append(line.strip())

highscores.append(wins)
highscores = sorted(highscores, key=int, reverse=True)
# Print sorted highscores print to file
with open("highscore.txt", "w") as f:
  for val in highscores:
    print(val, file=f)

Now I have a file with records stored in the form int /t string on each line (with a header). I'm not experienced in reading or sorting arrays with tuples and have no idea on how to approach this. Could anyone set me on the right path or provide a solution.

I'd like to read the int /t string record from my file and put it into the highscores array. Then I'd like to sort the array based off of the int value which is the first element of the tuple (assuming I don't take another approach). Then overwriting the file with the new highscore records.

Edit:

I should not that when I wrote highscore.append(wins) , wins is an integer variable I would like to append wins and name (the string as my variable).

You don't have to change much:

 highscores = sorted(highscores, key=lambda s: int(s.split()[0]), reverse=True)

The key function will take your line s . Then it will split it, take the first part and then convert it to an integer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM