Python Forum
Converting parts of a list to int for sorting - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Converting parts of a list to int for sorting (/thread-22199.html)



Converting parts of a list to int for sorting - menator01 - Nov-03-2019

I've been struggling with this for a couple of days now
I'm trying to pull a list from a text file in the format below
convert the numbers to int and sort by the numbers and not the str.
I can pull the numbers only and get it to work but when trying to put them back in
I get that it has to be a string. Any help would be great.
The goal is to pull the lines of text sort by the number then write them back to the text file.

Thanks

# text file list ['13,pops','15,bubble','150,nano','33,party','pokey']

def getIt():
    lst = []
    with open("scores.txt", "r")as file:
        data = file.read().splitlines()



    newlst = data.copy()
  
    print(sorted(newlst, key=lambda x: int(x[0].split(",")[0])))

    
##    conv = []   
##
##    for info in data:
##        conv.append(int(info.split(",")[0]))
##
##    print(sorted(conv, reverse = True))
##       
##    print(data)
    
#newdata = data.copy()



getIt()



RE: Converting parts of a list to int for sorting - AlekseyPython - Nov-03-2019

If your txt- file look like this (you made a mistake in the last line, forgetting the number):
Quote:13,pops
15,bubble
150,nano
33,party
11,pokey

then you can do this:
def getIt():
    with open("Text File.txt", "r")as file:
        data = file.read().splitlines()
 
    data.sort(key=lambda x: int(x.split(",")[0]), reverse = True)
    
    with open("Text File.txt", "w")as file:
        for element in data:
            file.write(element + '\n')

getIt()
Output:
150,nano 33,party 15,bubble 13,pops 11,pokey



RE: Converting parts of a list to int for sorting - menator01 - Nov-03-2019

Thanks a ton