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というのがある。