Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting strings by a substring in Python [duplicate]

I have a list of strings in python that looks like this:

  • Name number number 4-digit number

How can I sort it by the last number?

like image 225
user2308001 Avatar asked Apr 22 '13 15:04

user2308001


2 Answers

Like that:

sorted(your_list, lambda x: int(x.split()[-1]))
like image 72
aldeb Avatar answered Nov 09 '22 05:11

aldeb


my_list = ['abc 12 34 3333',
           'def 21 43 2222',
           'fgh 21 43 1111']

my_list.sort(key=lambda x:int(x.split()[-1]))

my_list is now: ['fgh 21 43 1111', 'def 21 43 2222', 'abc 12 34 3333']

like image 44
eumiro Avatar answered Nov 09 '22 07:11

eumiro