按文件基本名称对路径列表进行排序(Python) [英] Sort list of paths by file basename (Python)
问题描述
我有一个包含图像的文件夹. 我将每个图像的路径添加到列表中.它们不是按字母顺序排序的. 我对该函数进行了排序,但是排序后打印列表时的结果是相同的.
I have a folder with images. I added to a list the paths for each image. They are not alphabetically sorted. I made this function to sort but I the result it's the same when I print the list after sorting.
import os
import glob
images_path = os.path.expanduser('~\\Desktop\\samples\\')
def img_path_list():
img_list = []
for file_path in glob.glob(str(images_path) + "*.jpg"):
img_list.append(file_path)
img_list.sort(key=lambda x: str(x.split('.')[0]))
return img_list
print(img_path_list())
结果仍然是[Desktop\\t0.jpg, Desktop\\t1.jpg, Desktop\\t10.jpg, Desktop\\t11.jpg, Desktop\\t2.jpg, ...]
只要我不要求使用natsort
模块,而是简单的python,就不会重复.
not a duplicate as long as I didn't request to use natsort
module but with simple python.
推荐答案
使用os.path.basename
并假设您的文件名都是X#.jpg
格式,其中X
是单个字符:
Using os.path.basename
and assuming your filenames are all of the format X#.jpg
with X
a single character:
import os
img_list = ['Desktop\\t0.jpg', 'Desktop\\t1.jpg',
'Desktop\\t10.jpg', 'Desktop\\t11.jpg',
'Desktop\\t2.jpg']
img_list.sort(key=lambda x: int(os.path.basename(x).split('.')[0][1:]))
print(img_list)
['Desktop\\t0.jpg', 'Desktop\\t1.jpg',
'Desktop\\t2.jpg', 'Desktop\\t10.jpg',
'Desktop\\t11.jpg']
使用命名函数来说明lambda
的工作方式:
With a named function to illustrate how lambda
works:
def sorter(x):
return int(os.path.basename(x).split('.')[0][1:])
img_list.sort(key=sorter)
说明
这里有一些步骤:
- 通过
os.path.basename
提取文件名. - 由
.
分割并提取第一个元素. - 然后从第一个字符开始进行切片.
- 将结果转换为
int
以进行数字排序.
- Extract the filename via
os.path.basename
. - Split by
.
and extract first element. - Then slice by 1st character onwards.
- Convert the result to
int
for numerical ordering.
这篇关于按文件基本名称对路径列表进行排序(Python)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!