I have a list that has some chapter numbers in string. When I sort the keys using keys function, it gives me wrong results.
keys = ['1.1', '1.2', '2.1', '10.1'] keys.sort() print keys ['1.1', '1.2', '10.1', '2.1']
How can I use the sort function to get
['1.1', '1.2', '2.1', '10.1']
What if the array has something like this?
['1.1.1', '1.2.1', '10.1', '2.1'] -> ['1.1.1','1.2.1','2.1','10.1']
In Python, you can sort a list with the sort() method or the sorted() function. This article describes how to sort a list of numeric strings not filled with zeros.
Use the Python List sort() method to sort a list in place. The sort() method sorts the string elements in alphabetical order and sorts the numeric elements from smallest to largest. Use the sort(reverse=True) to reverse the default sort order.
Python sorted() Function The sorted() function returns a sorted list of the specified iterable object. You can specify ascending or descending order. Strings are sorted alphabetically, and numbers are sorted numerically.
keys.sort(key=lambda x: [int(y) for y in x.split('.')])
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