如何对数字文件名进行排序?

时间:2018-11-09 11:44:11

标签: python python-3.x sortedlist

有一个文件夹,其中包含一些要排序的图像(切片)。文件夹中排序的文件名的一个示例是:

  0.7.dcm
 -1.1.dcm
  2.5.dcm
 -2.9.dcm
 -4.7.dcm
 -6.5.dcm
 -8.3.dcm
 -10.1.dcm

其中一些是:

 -10.000000.dcm
 -12.500000.dcm
 -15.000000.dcm
 -17.500000.dcm
 -20.000000.dcm
 -22.500000.dcm
 -25.000000.dcm
 -27.500000.dcm

但是,当我想阅读它们时,它们会作为未排序的列表加载。我尝试了一些方法,但问题尚未解决:

for person in range(0, len(dirs1)):
    for root, dirs, files in os.walk(os.path.join(path, dirs1[person])):
        dcmfiles = [_ for _ in files if _.endswith('.dcm')]  # ['-10.000000.dcm', '-22.500000.dcm', '-17.500000.dcm', '-27.500000.dcm', '-25.000000.dcm', '-12.500000.dcm', '-20.000000.dcm', '-15.000000.dcm']
        dcmfilesList = sorted(dcmfiles, key = lambda x: x[:-4]) # ['-10.000000.dcm', '-22.500000.dcm', '-17.500000.dcm', '-27.500000.dcm', '-25.000000.dcm', '-12.500000.dcm', '-20.000000.dcm', '-15.000000.dcm']

我也选中了Sort filenames1Sort filenames2Sort filenames3

如何读取python3中排序的.dcm切片,如下所示?

['0.7.dcm', '-1.1.dcm', '2.5.dcm', '-2.9.dcm', '-4.7.dcm', '-6.5.dcm', -8.3.dcm', '-10.1.dcm'].

 ['-10.000000.dcm', '-12.500000.dcm', '-15.000000.dcm', '-17.500000.dcm', '-20.000000.dcm', '-22.500000.dcm', '-25.000000.dcm',  '-27.500000.dcm'].

2 个答案:

答案 0 :(得分:2)

您没有在排序之前将它们转换为数字,所以它不起作用。

import os

for root, dirs, files in os.walk('./'):
        dcmfiles = [_ for _ in files if _.endswith('.dcm')]
        dcmFilesList = sorted(dcmfiles, key=lambda x: float(x[:-4]))

要对忽略符号进行排序,请lambda x: abs(float(x[:-4]))

答案 1 :(得分:0)

您可以先按文件名的浮点前缀对文件列表进行排序,仅包括.dcm文件扩展名,然后分别打开每个文件:

from os import walk
from os.path import splitext

# sort .dcm files by file prefix
sorted_files = sorted(
    (file for _, _, files in walk(".") for file in files if file.endswith(".dcm")),
    key=lambda f: float(splitext(f)[0]),
)

# open each .dcm file and do some processing
for file in sorted_files:
    with open(file) as dcm_file:
        # do reading stuff here