1
1

More than 3 years have passed since last update.

pythonで文字列を自然順(番号が小さい順)ソート

Posted at

sortedは辞書順になってしまい、数値が小さい順に並ばない。
正規表現を使えば簡単に自然順にできるけど、毎回書くのが面倒なのでメモ。

文字列の場合

l = ['1', '10', '2']

import re
sorted(l, key=lambda x: tuple(map(int, re.findall(r'\d+', x))))

文字列じゃない場合(pathlib.Pathなど)

from pathlib import Path
l = [Path('1'), Path('10'), Path('2')]

import re
sorted(l, key=lambda x: tuple(map(int, re.findall(r'\d+', str(x)))))

ライブラリを使う場合

natsortというのがある。

1
1
1

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
1
1