【问题标题】:Sort a list of strings containing numbers at the start of the list by the numbers in the strings in Python按Python中字符串中的数字对列表开头包含数字的字符串列表进行排序
【发布时间】:2020-05-11 10:09:49
【问题描述】:

我的目录中有一个HTML 文件列表,使用glob 获得,它们的模式为numb-filenames。我想通过数字sort list

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))

【问题讨论】:

  • 您的解决方案几乎在那里:re.findall 将返回一个字符串列表,因此它们仍将作为字符串排序,然后您需要将它们转换为数字,以便它们按数字排序。一个完整的findall 也太过分了,因为你只有一个数字,search/match 甚至一个简单的str.split 都可以。

标签: python python-3.x string list


【解决方案1】:
sorted(data, key=lambda x: int(x.split('-')[0]))

我们在 '-' 处拆分字符串并获取包含字符串格式数字的第一部分 - 然后将其转换为 int 类型并将其用作对列表进行排序的键。

【讨论】:

  • split('-', 1) 可能会更好,因为您只想要拆分的第一部分。
【解决方案2】:

你可以的

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

这将根据文件名开头的数字对所有文件进行排序。
输出

['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']

【讨论】:

    猜你喜欢
    • 2017-08-11
    • 2021-08-12
    • 2021-08-02
    • 2018-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-22
    • 1970-01-01
    相关资源
    最近更新 更多