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()
I welcome all feedback.
The only dumb question, is one that doesn't get asked.
My Github
How to post code using bbtags


Reply


Messages In This Thread
Converting parts of a list to int for sorting - by menator01 - Nov-03-2019, 01:57 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  List Sorting Problem ZZTurn 5 1,480 Sep-22-2022, 11:23 PM
Last Post: ZZTurn
  Sorting List finndude 9 2,619 Jan-27-2022, 09:37 PM
Last Post: Pedroski55
  sorting a list of lists by an element leapcfm 3 2,023 Sep-10-2021, 03:33 PM
Last Post: leapcfm
  Converting a list to dictinary tester_V 8 2,866 Jul-02-2021, 09:04 PM
Last Post: tester_V
  Converting tkinter listbox into list BigSwiggy 6 3,835 Feb-07-2021, 02:01 PM
Last Post: BigSwiggy
  Sorting list of names using a lambda (PyBite #5) Drone4four 2 2,828 Oct-16-2020, 07:30 PM
Last Post: ndc85430
  Converting list to variables Palves 1 1,846 Sep-18-2020, 05:43 PM
Last Post: stullis
  Trouble with converting list , dict to int values! faryad13 7 3,911 Sep-04-2020, 06:25 AM
Last Post: faryad13
  list sorting question DPaul 5 2,922 Jun-17-2020, 02:23 PM
Last Post: ndc85430
  converting list of zero length to a matrix of 3*3 vp1989 2 2,030 May-20-2020, 07:46 PM
Last Post: deanhystad

Forum Jump:

User Panel Messages

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