简体   繁体   English

按 Python 中字符串中的数字对列表开头包含数字的字符串列表进行排序

[英]Sort a list of strings containing numbers at the start of the list by the numbers in the strings in Python

I have a list of HTML files in my directory obtained using the glob and they have the pattern numb-filenames .我在使用glob获得的目录中有一个HTML文件列表,它们具有模式numb-filenames I would like to sort the list by the numbers我想按数字对list进行sort

The len of the string is 76. I could not copy all of it but here are a few of them: stringlen是 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']

Here is my attempt:这是我的尝试:

sorted(df, key=lambda x: re.findall("\d+",x))
sorted(data, key=lambda x: int(x.split('-')[0]))

We are splitting the string at '-' and fetching the first part which consists of number in string format - then casting it to int type and using it as a key to sort the list.我们在 '-' 处拆分字符串并获取包含字符串格式数字的第一部分 - 然后将其转换为 int 类型并将其用作对列表进行排序的键。

You can do你可以做

sorted(df, key=lambda x: int(x[:x.find('-')]))

That will sort you all the files base on the number in the beginning of the file name.这将根据文件名开头的数字对所有文件进行排序。
Output 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM