python - 按升序对目录中的文件名进行排序

标签 python sorting

我有一个目录,里面有 jpg 和其他文件,这些 jpg 都有文件名,里面有数字。有些可能在文件名中有额外的字符串。

例如。

01.jpg

也可以

Picture 03.jpg

在 Python 中,我需要按升序排列的所有 jpg 列表。 这是这个的代码片段

import os
import numpy as np

myimages = [] #list of image filenames
dirFiles = os.listdir('.') #list of directory files
dirFiles.sort() #good initial sort but doesnt sort numerically very well
sorted(dirFiles) #sort numerically in ascending order

for files in dirFiles: #filter out all non jpgs
    if '.jpg' in files:
        myimages.append(files)
print len(myimages)
print myimages

我得到的是这个

['0.jpg', '1.jpg', '10.jpg', '11.jpg', '12.jpg', '13.jpg', '14.jpg',
 '15.jpg', '16.jpg', '17.jpg', '18.jpg', '19.jpg', '2.jpg', '20.jpg',
 '21.jpg', '22.jpg', '23.jpg', '24.jpg', '25.jpg', '26.jpg', '27.jpg',
 '28.jpg', '29.jpg', '3.jpg', '30.jpg', '31.jpg', '32.jpg', '33.jpg',
 '34.jpg', '35.jpg', '36.jpg', '37.jpg', '4.jpg', '5.jpg', '6.jpg',
 '7.jpg', '8.jpg', '9.jpg']

显然,它首先对最重要的数字进行盲目排序。我尝试使用 sorted() 如您所见,希望它能修复它,但没有任何区别。

最佳答案

假设每个文件名中只有一个数字:

>>> dirFiles = ['Picture 03.jpg', '02.jpg', '1.jpg']
>>> dirFiles.sort(key=lambda f: int(filter(str.isdigit, f)))
>>> dirFiles
['1.jpg', '02.jpg', 'Picture 03.jpg']

同样适用于 Python 3 的版本:

>>> dirFiles.sort(key=lambda f: int(re.sub('\D', '', f)))

关于python - 按升序对目录中的文件名进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33159106/

相关文章:

python - 在 wxPython 中覆盖 KeyDown 事件

python - 字符串列表 - 删除常见字符串的共性

python - 如何在 Sublime Text 3 上安装 pandas

java - 冒泡排序日历

javascript - Tablesorter - 按 td 类排序

algorithm - 如何有效地对有序序列数组进行排序

python - Keras flow_from_dataframe 给出 0 个图像

python - 在另一个 python 文件中访问 Flask 应用程序端点?

algorithm - 不使用循环对字符串列表进行排序的伪代码

java - 在Java中,如何使用我自己的比较标准对未实现Comparable的对象进行排序?