user1083734 user1083734 - 2 months ago 9
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

name.1
name.2
name.4
name.13
name.32


What I have tried so far is:

print sorted(my_list)

name.1
name.13
name.2
name.32
name.4


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

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
'l','name.1'
'i','name.2'
's','name.4'
't','name.13'
's','name.32'


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

Alex

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.