首页 > 解决方案 > 按数字对图像文件名列表进行排序

问题描述

我正在尝试订购以下图像序列列表。即frame0.jpg --> frame17.jpg

我曾尝试拆分名称,然后对它们进行排序,但它不起作用。

这是我的代码:

Data = [
    "D:\\shooting_videos\\example\\Output\\trained_framesmake2\\frame0.jpg",
    "D:\\shooting_videos\\example\\Output\\trained_framesmake2\\frame1.jpg",
    "D:\\shooting_videos\\example\\Output\\trained_framesmake2\\frame10.jpg",
    "D:\\shooting_videos\\example\\Output\\trained_framesmake2\\frame11.jpg",
    "D:\\shooting_videos\\example\\Output\\trained_framesmake2\\frame12.jpg",
    "D:\\shooting_videos\\example\\Output\\trained_framesmake2\\frame13.jpg",
    "D:\\shooting_videos\\example\\Output\\trained_framesmake2\\frame14.jpg",
    "D:\\shooting_videos\\example\\Output\\trained_framesmake2\\frame15.jpg",
    "D:\\shooting_videos\\example\\Output\\trained_framesmake2\\frame16.jpg",
    "D:\\shooting_videos\\example\\Output\\trained_framesmake2\\frame17.jpg",
    "D:\\shooting_videos\\example\\Output\\trained_framesmake2\\frame2.jpg",
    "D:\\shooting_videos\\example\\Output\\trained_framesmake2\\frame3.jpg",
    "D:\\shooting_videos\\example\\Output\\trained_framesmake2\\frame4.jpg",
    "D:\\shooting_videos\\example\\Output\\trained_framesmake2\\frame5.jpg",
    "D:\\shooting_videos\\example\\Output\\trained_framesmake2\\frame6.jpg",
    "D:\\shooting_videos\\example\\Output\\trained_framesmake2\\frame7.jpg",
    "D:\\shooting_videos\\example\\Output\\trained_framesmake2\\frame8.jpg",
    "D:\\shooting_videos\\example\\Output\\trained_framesmake2\\frame9.jpg",
]

sorted_Data = sorted(Data, key=lambda x: int(x.split('.')[0]))

标签: python-3.xsorting

解决方案


您可以使用 regex (\d+)\.[a-z]+$,它在文件扩展名之前捕获数字,假设是按字母顺序排列的。

import re

sorted(data, key=lambda x: int(re.search(r"(\d+)\.[a-z]+$", x).group(1)))

推荐阅读