T0m T0m - 4 months ago 11
Python Question

Sorting complex list of strings in python

I feel it would be better to illustrate my problem, so here it is:

I have this list:

['1.2.3', '1.2.4', '10.3', '1.3', '12', '14.12.123', '4', '6']

and would like it sorted like so:

['1.2.3', '1.2.4', '1.3', '4', '6', '10.3', '12', '14.12.123']

As you can see I would like to sort initially by the first digit then the second and so on. Also there could be an infinite amount of digits in the list items(e.g.
and so on)

I have tried the usual sorted method to no avail, and cannot find a similar situation on the internet to help me out.

Thanks for your help.


This should do it:

sorted(l, key=lambda k: [int(num) for num in k.split('.')])