Python Forum
Converting parts of a list to int for sorting
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Converting parts of a list to int for sorting
#1
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()

Reply
#2
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
Reply
#3
Thanks a ton
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Sorting list of names using a lambda (PyBite #5) Drone4four 2 236 Oct-16-2020, 07:30 PM
Last Post: ndc85430
  put an image into 3 parts Nickd12 4 377 Sep-30-2020, 11:00 PM
Last Post: Nickd12
  Converting list to variables Palves 1 259 Sep-18-2020, 05:43 PM
Last Post: stullis
  Trouble with converting list , dict to int values! faryad13 7 425 Sep-04-2020, 06:25 AM
Last Post: faryad13
  list sorting question DPaul 5 401 Jun-17-2020, 02:23 PM
Last Post: ndc85430
  converting list of zero length to a matrix of 3*3 vp1989 2 345 May-20-2020, 07:46 PM
Last Post: deanhystad
  sorting list of lists pframe 5 578 Apr-17-2020, 09:31 PM
Last Post: Larz60+
  converting string object inside a list into an intiger bwdu 4 446 Mar-31-2020, 10:36 AM
Last Post: buran
  sorting list arian29 2 465 Feb-02-2020, 10:31 AM
Last Post: ndc85430
  more list help converting paul41 3 563 Nov-25-2019, 07:59 AM
Last Post: perfringo

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020