Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Specific sort a list of numbers separated by dots

I have a list:

L = ['1.1.1.', '1.1.10.', '1.1.11.', '1.1.12.', '1.1.13.', '1.1.2.', '1.1.3.', '1.1.4.']

I want to sort it in next order:

1.1.1.
1.1.2.
1.1.3.
1.1.4.
1.1.10.
1.1.11.
1.1.12.
1.1.13.

The following method does not produce a result:

L.sort(key=lambda s: int(re.search(r'.(\d+)',s).group(1)))
like image 956
Vadim Kiselev Avatar asked Jan 26 '14 09:01

Vadim Kiselev


2 Answers

Just get the last part, convert that to an int and return it as the key for comparison

print(sorted(L, key=lambda x: int(x.split(".")[2])))

If you want all the parts to be considered, you can do like this

print(sorted(L, key=lambda x: [int(i) for i in x.rstrip(".").split(".")]))

It removes . at the end of the strings, splits them based on . and then converts each and every part of it to an int. The returned list will be used for comparison.

You can read more about how various sequences will be compared by Python, here

Output

['1.1.1.','1.1.2.','1.1.3.','1.1.4.','1.1.10.','1.1.11.','1.1.12.','1.1.13.']
like image 134
thefourtheye Avatar answered Sep 16 '22 21:09

thefourtheye


If you need to sort by all digits, produce a sequence of integers in the key function:

sorted(L, key=lambda v: [int(p) for p in v.split('.') if p.isdigit()])

This method is robust in the face of non-digit values between the dots.

Demo:

>>> L = ['1.1.1.', '1.1.10.', '1.1.11.', '1.1.12.', '1.1.13.', '1.1.2.', '1.1.3.', '1.1.4.']
>>> sorted(L, key=lambda v: [int(p) for p in v.split('.') if p.isdigit()])
['1.1.1.', '1.1.2.', '1.1.3.', '1.1.4.', '1.1.10.', '1.1.11.', '1.1.12.', '1.1.13.']

Your specific attempt only returns the second number in the list, which for your sample data is always 1.

like image 41
Martijn Pieters Avatar answered Sep 16 '22 21:09

Martijn Pieters