[英]Sort a list of strings containing numbers at the start of the list by the numbers in the strings in Python
我在使用glob
获得的目录中有一个HTML
文件列表,它们具有模式numb-filenames
。 我想按数字对list
进行sort
string
的len
是 76。我无法全部复制,但这里有一些:
['50-Rcompat.html',
'51-tang.html',
'52-rectgw.html',
'53-wea.html',
'54-PTect.html',
'55-R+V Allg.html',
'56-SafetyCa.html',
'57-TEI.html',
'58-TAS.html',
'59-TrPr.html',
'6-sde.html',
'60-weac.html',
'61-WKra.html',
'62-KCV .html',
'63-Wdenbu.html',
'64-TGARA.html',
'65-BiV.html',
'66-BURG.html',
'67-richI.html',
'7-pril.html',
'8-spario.html',
'9-Weal.html']
这是我的尝试:
sorted(df, key=lambda x: re.findall("\d+",x))
sorted(data, key=lambda x: int(x.split('-')[0]))
我们在 '-' 处拆分字符串并获取包含字符串格式数字的第一部分 - 然后将其转换为 int 类型并将其用作对列表进行排序的键。
你可以做
sorted(df, key=lambda x: int(x[:x.find('-')]))
这将根据文件名开头的数字对所有文件进行排序。
Output
['6-sde.html',
'7-pril.html',
'8-spario.html',
'9-Weal.html',
'50-Rcompat.html',
'51-tang.html',
'52-rectgw.html',
'53-wea.html',
'54-PTect.html',
'55-R+V Allg.html',
'56-SafetyCa.html',
'57-TEI.html',
'58-TAS.html',
'59-TrPr.html',
'60-weac.html',
'61-WKra.html',
'62-KCV .html',
'63-Wdenbu.html',
'64-TGARA.html',
'65-BiV.html',
'66-BURG.html',
'67-richI.html']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.