user1083734 user1083734 - 7 months ago 28
Python Question

What is the best way to sort this list?

I have the following list:

my_list = ['name.13','name.1', 'name.2','name.4', 'name.32']

And I would like sort the list and print it out in order, like this


What I have tried so far is:

print sorted(my_list)


The sorted() command obviously treats the string alphabetically. Maybe it would be better to sort numerically after detecting the

Is there an good way to sort it properly? What would be the most efficient approach to take? How would I apply this is I had a list of tuples and wanted to sort it using the second elemnt of the tuples? For instance:

tuple_list = [('i','name.2'),('t','name.13'),('s','name.32'),('l','name.1'),('s','name.4')]

print tuple_list

Thanks for your help and, as always, comment if you think the question can be improved/clarified.


Answer Source

You could try it similarly to this answer:

>>> my_list = ['name.13','name.1', 'name.2','name.4', 'name.32']
>>> sorted(my_list, key=lambda a: (int(a.split('.')[1])))
['name.1', 'name.2', 'name.4', 'name.13', 'name.32']

Or with tuples:

>>> tuple_list = [('i','name.2'),('t','name.13'),('s','name.32'),('l','name.1'),('s','name.4')]
>>> sorted(tuple_list, key=lambda (a,b): (int(b.split('.')[1])))
[('l', 'name.1'), ('i', 'name.2'), ('s', 'name.4'), ('t', 'name.13'), ('s', 'name.32')]

Edit to explain what this does:

The example passes a lambda function to sorted that splits the strings and then converts the second part to an integer. sorted then uses this integer to sort the list items.

This example completely ignores the strings to the left of the dot when sorting. Please let me know if you also need to sort by the first part.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download