I'm trying to display some results in a human-readable way. For the purposes of this question, some of them are numbers, some are letters, some are a combination of the two.
I'm trying to figure out how I could get them to sort like this:
input = ['1', '10', '2', '0', '3', 'Hello', '100', 'Allowance']
sorted_input = sorted(input)
print(sorted_input)
Desired Results:
['0', '1', '2', '3', '10', '100', 'Allowance', 'Hello']
Actual results:
['0', '1', '10', '100', '2', '3', 'Allowance', 'Hello']
I'm having trouble coming up with how to do this.
1 - Install natsort module
pip install natsort
2 - Import natsorted
>>> input = ['1', '10', '2', '0', '3', 'Hello', '100', 'Allowance']
>>> from natsort import natsorted
>>> natsorted(input)
['0', '1', '2', '3', '10', '100', 'Allowance', 'Hello']
Source: https://pypi.python.org/pypi/natsort
I have found the code in the following link about natural sorting order very useful in the past:
http://www.codinghorror.com/blog/2007/12/sorting-for-humans-natural-sort-order.html
This will do it. For purposes of comparison, it converts strings that can be converted to an integer to that integer, and leaves other strings alone:
def key(s):
try:
return int(s)
except ValueError:
return s
sorted_input = sorted(input, key=key)
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