Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort list depending on substring?

Tags:

python

django

I have this list sorted:

>>> L = ['actor_1', 'actor_3', 'actor_130', 'actor_55', 'actor_5']
>>> L.sort()
>>> L
['actor_1', 'actor_130', 'actor_3', 'actor_5', 'actor_55']

Is there a clean way to make the list sortable by the number after underline to have it like the following?:

['actor_1', 'actor_3', 'actor_5', 'actor_55', 'actor_130']
like image 948
Drwhite Avatar asked Dec 16 '22 06:12

Drwhite


1 Answers

You can specify key function which generate comparison key:

>>> L = ['actor_1', 'actor_3', 'actor_130', 'actor_55', 'actor_5']
>>> def sort_key(s):
...     s, n = s.split('_')
...     return s, int(n)
...
>>> L.sort(key=sort_key)
>>> L
['actor_1', 'actor_3', 'actor_5', 'actor_55', 'actor_130']
like image 197
falsetru Avatar answered Dec 17 '22 21:12

falsetru