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']
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']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With