Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort results non-lexicographically?

Tags:

python

sorting

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.

like image 615
user2923558 Avatar asked Oct 27 '13 23:10

user2923558


3 Answers

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

like image 181
Mingyu Avatar answered Nov 15 '22 17:11

Mingyu


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

like image 30
Ben Avatar answered Nov 15 '22 16:11

Ben


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)
like image 36
Tim Peters Avatar answered Nov 15 '22 18:11

Tim Peters