0

I would like to sort this list:

my_list = ["32,6,bob", "5,21,fred", "100,9,sid"]

by the second number in each string in descending order. Like this:

["5,21,fred", "100,9,sid", "32,6,bob"]

I know I can change it to a list of lists and sort it like this:

my_list = [["32", "6", "bob"], ["5", "21", "fred"], ["100", "9", "sid"]]
my_list.sort(reverse=True, key=lambda x: x[1])

But it's annoying to have to change it to lists and then string it afterwards (It's to be written to a file), so I was wondering if there's a way to sort it as strings.

2
  • On a side note, your code would be incorrect, you are sorting lexicographically not by the actual number value Commented Apr 18, 2016 at 15:49
  • Thanks for letting me know. Commented Apr 18, 2016 at 16:33

1 Answer 1

5
In [1]: sorted(["32,6,bob", "5,21,fred", "100,9,sid"],
   ...:        key=lambda s: int(s.split(',')[1]),
   ...:        reverse=True)
Out[1]: ['5,21,fred', '100,9,sid', '32,6,bob']
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.