简体   繁体   中英

Python: How do i sort integers in a text file into ascending and/or descending order?

I have a text file(data.txt) containing names and scores 1:1 ie:

Mike = 1\n John = 2\n Cam = 3\n

I want to sort the integers along with the corresponding name in ascending and descending order.

with open(filepath, 'r') as file:
    list = []
    for line in file:
        list.append(line[1:-1].split(","))
list.sort(key=lambda x: int(x[4]))

Yes, i have done some research however it doesn't work, i was hoping one of you guys could help me fix the code above. I know i must convert the data within the text file into a list then sort the list then put write back to the text file, but i am not sure how. Source: How do i sort a text file numerically highest to lowest?

Here's an example, doing it in memory using the sorted() function.

with open(filepath, 'r') as file:
    sorted_data=sorted(file.readlines(), 
                       key=lambda item: int(item.rsplit('=',1)[-1].strip()))

sorted_data will then contain a list of the sorted rows.

Here it is:

open the file:

with open(filepath, 'r') as file:

Get all the lines of the file (as a list):

file.readlines()

For each line in the file, sorted() will numerically sort them based on the output of passing each line into the "key" function.

The "key" function takes a line, splits it by the "=" symbol, then takes the last part of that (the part after the = sign), strips any leading or trailing whitespace (.strip()) and returns the value cast to an integer (int) .

Sorted takes the lines and orders them using the numbers output by the key function.

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