LoginSignup
5
5

More than 3 years have passed since last update.

ナチュラルソート

Posted at

以下の変数を並び替える状況があるとする。

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

例えば組み込み関数の sorted を利用すると

sorted(sample)

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

という結果が得られる。これは人間の直感には反する結果だろう。

['a_0', 'a_2', 'a_4', 'a_10', 'a_12'] という結果が得られる方が自然な感じがする。
この自然な感じがする並びは、 Natural Sort Order と呼ばれ、そのソート方法はHuman Sortingとも呼ばれる。

この並び順をpythonで再現する。

ライブラリを利用する場合

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']

自分で関数を書く場合

組み込み関数の sorted にkeyを指定すれば良い。

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']
5
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
5