標籤:strong spl https pre split key 遍曆 png div
import osimport redef sorted_aphanumeric(data): convert = lambda text: int(text) if text.isdigit() else text.lower() alphanum_key = lambda key: [ convert(c) for c in re.split(‘([0-9]+)‘, key) ] return sorted(data, key=alphanum_key)file = sorted_aphanumeric(os.listdir("./2"))for f in file: print(f)
參考
https://stackoverflow.com/questions/4813061/non-alphanumeric-list-order-from-os-listdir
Python for whatever reason does not come with a built-in way to have natural sorting (meaning 1, 2, 10 instead of 1, 10, 2), so you have to write it yourself:
import redef sorted_aphanumeric(data): convert = lambda text: int(text) if text.isdigit() else text.lower() alphanum_key = lambda key: [ convert(c) for c in re.split(‘([0-9]+)‘, key) ] return sorted(data, key=alphanum_key)
You can now use this function to sort a list:
dirlist = sorted_aphanumeric(os.listdir(...))
python 按照自然數排序遍曆檔案 python os.listdir sort by natural sorting