T0m T0m - 1 year ago 92
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.

Answer Source

This should do it:

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

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