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

How to sort numeric file names?

有一个文件夹,里面有一些图像(切片),它们是排序的。文件夹中排序的文件名示例是:

  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']

我还检查了 , ,

如何读取在 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'].

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

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]))

您可以先按浮点前缀对文件列表进行排序,只包括 .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