Jack
Jack

Reputation: 17

Python - How to sort a list of strings

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.

Upvotes: 0

Views: 77

Answers (1)

BlackBear
BlackBear

Reputation: 22979

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']

Upvotes: 5

Related Questions