[英]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.