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
#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


Messages In This Thread
RE: Converting parts of a list to int for sorting - by AlekseyPython - Nov-03-2019, 02:45 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  List Sorting Problem ZZTurn 5 1,384 Sep-22-2022, 11:23 PM
Last Post: ZZTurn
  Sorting List finndude 9 2,506 Jan-27-2022, 09:37 PM
Last Post: Pedroski55
  sorting a list of lists by an element leapcfm 3 1,919 Sep-10-2021, 03:33 PM
Last Post: leapcfm
  Converting a list to dictinary tester_V 8 2,754 Jul-02-2021, 09:04 PM
Last Post: tester_V
  Converting tkinter listbox into list BigSwiggy 6 3,662 Feb-07-2021, 02:01 PM
Last Post: BigSwiggy
  Sorting list of names using a lambda (PyBite #5) Drone4four 2 2,758 Oct-16-2020, 07:30 PM
Last Post: ndc85430
  Converting list to variables Palves 1 1,782 Sep-18-2020, 05:43 PM
Last Post: stullis
  Trouble with converting list , dict to int values! faryad13 7 3,795 Sep-04-2020, 06:25 AM
Last Post: faryad13
  list sorting question DPaul 5 2,793 Jun-17-2020, 02:23 PM
Last Post: ndc85430
  converting list of zero length to a matrix of 3*3 vp1989 2 1,947 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