MarkF6
MarkF6

Reputation: 503

Python: Sort lists in lists numerically

I have a list like this one:

list1 = [['art_25', 'title', 'author'], ['art_12', 'title', 'author'], ['art_4', 'title', 'author']]

How can I sort this list s.t. the output equals

[['art_4', 'title', 'author'], ['art_12' ...], ['art_25', ...]] ?

Thanks for any help!

Upvotes: 1

Views: 68

Answers (1)

Cory Kramer
Cory Kramer

Reputation: 117876

You can use sorted with the key parameter. You can make a lambda expression that splits on the '_' character, turns it into an int then sorts by that value.

list1 = [['art_25', 'title', 'author'],
         ['art_12', 'title', 'author'],
         ['art_4', 'title', 'author']]

>>> sorted(list1, key=lambda i: int(i[0].split('_')[1]))
[['art_4', 'title', 'author'],
 ['art_12', 'title', 'author'],
 ['art_25', 'title', 'author']]

Upvotes: 5

Related Questions