LoginSignup
1
0

More than 1 year has passed since last update.

数値を含む文字列のリストを昇順に並べ替える

Posted at

綺麗に並べたい

globしたファイルの読み取り時など、ファイル名順に読み取りたかったりします。

二桁以上は注意

sortedをそのまま使うと、桁が上がった時に、昇順になりません。

files = ['11.jpg','7.jpg', '5.jpg', '9.jpg', '2.jpg', '6.jpg', '10.jpg', '1.jpg', '8.jpg', '4.jpg',  '3.jpg', '12.jpg']

sorted(files)

['1.jpg',
'10.jpg',
'11.jpg',
'12.jpg',
'2.jpg',
'3.jpg',
'4.jpg',
'5.jpg',
'6.jpg',
'7.jpg',
'8.jpg',
'9.jpg']

解決法

import re
def atoi(text):
    return int(text) if text.isdigit() else text

def natural_keys(text):
    return [ atoi(c) for c in re.split(r'(\d+)', text) ]

sorted_files = sorted(files,key=natural_keys)
sorted_files

['1.jpg',
'2.jpg',
'3.jpg',
'4.jpg',
'5.jpg',
'6.jpg',
'7.jpg',
'8.jpg',
'9.jpg',
'10.jpg',
'11.jpg',
'12.jpg']

🐣


フリーランスエンジニアです。
お仕事のご相談こちらまで
rockyshikoku@gmail.com

機械学習、ARアプリ(Web/iOS)を作っています。
機械学習/AR関連の情報を発信しています。

Twitter
Medium
GitHub

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