Sort filenames by numbers in the name with lambda

All the filenames are in the format ‘frame_xxx.jpg’, like
在这里插入图片描述
When I got all these filenames by os.listdir() and put them in a list. Their order is uncorrect.
The code I got all the filenames are shown as following.

在这里插入图片描述
The list saved all the filenames are disordered.
在这里插入图片描述
Since they are frame names of a video, they should be processed in right order. So we have to sort the list before further processing.
The solution is using lambda expression to get the number of the framename and sort the list by the number. The code is shown as following.
在这里插入图片描述

There is no need to define a function. Supposing frames is the list you saved all the framenames, you can just use frames.sort(key=lambda i: int(re.findall(r'\d+', i)[0])) to sort the list. And finally you will get all framenames in right order.
在这里插入图片描述
There are some useful blogs for you to get a clear of lambda expression and the sort strategy.
Python 列表内字符串按照规则排序(字符串列表的排序)
搞清楚 Python 正则表达式,简单易懂看这一篇就够了
python正则表达式从字符串中提取数字的思路详解
玩转python的正则表达式|提取字符串中的所有数字

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值