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)))
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.']
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With