首页 > 解决方案 > 如何按数字顺序导入图像?

问题描述

我有这段代码可以从文件夹中导入图像,但图像按以下顺序排列:

test1.png
test10.png
test100.png
test101.png
test102.png
test103.png
test104.png
test105.png
test106.png
test107.png
test108.png
test109.png
test11.png
test110.png
test111.png
test112.png
test113.png
test114.png
test115.png
test116.png
test117.png
test118.png
test119.png
test12.png
etc...

我想要的顺序是test1, test2, test3, 等等...

我怎样才能做到这一点?

test_set = []
test_result=[]
test_dir= "C:/Users/anwer/Desktop/copy/test/"

for file in os.listdir(test_dir):
    test_set.append((give_peak_sum(test_dir+file), file))
    test_result.append((give_peak_sum(test_dir+file)))
    print(file)

标签: python

解决方案


您需要先对列表进行排序。

如果您的所有文件都以“测试”开头

你可以使用

yourlist.sort(key=lambda x: int(x.split('.')[0][4:]))

推荐阅读