[PYTHON] Natural sort

Suppose there is a situation where the following variables are sorted.

sample = ["a_12", "a_2", "a_0",  "a_10", "a_4"]

For example, if you use the built-in function sorted

sorted(sample)

# ['a_0', 'a_10', 'a_12', 'a_2', 'a_4']

The result is obtained. This would be contrary to human intuition.

It feels more natural to get the result ['a_0','a_2','a_4','a_10','a_12']. This natural sort order is called Natural Sort Order, and the sorting method is also called Human Sorting.

Reproduce this order in python.

When using the library

Use natsort.

https://pypi.org/project/natsort/

$ pip install natsort
sample = ["a_12", "a_2", "a_0",  "a_10", "a_4"]
print(sample)
print(natsorted(sample, key=lambda y: y.lower()))

# ['a_12', 'a_2', 'a_0', 'a_10', 'a_4']
# ['a_0', 'a_2', 'a_4', 'a_10', 'a_12']

If you write your own function

You can specify the key for the built-in function sorted.

def natural_sort(l):
    def alphanum_key(s):
        return [int(c) if c.isdecimal() else c for c in re.split('([0-9]+)', s) ]
    return sorted(l, key=alphanum_key)

print(sample)
print(natural_sort(sample))

# ['a_12', 'a_2', 'a_0', 'a_10', 'a_4']
# ['a_0', 'a_2', 'a_4', 'a_10', 'a_12']

Recommended Posts

Natural sort
sort
Insertion sort
Selection Sort
[Python] Sort
Python # sort
Bubble sort
Bubble sort
AOJ Sort I-
[Python] Sort the list of pathlib.Path in natural sort
Natural number generator
Merge Sort Explained
Insertion sort implementation
Hands-on sleep sort
Sort by pandas
visualize insertion sort