【问题标题】:How to sort s list of strings in python ignoring digits in those strings?python - 如何对python中的字符串列表进行排序,忽略这些字符串中的数字?
【发布时间】:2020-05-02 14:19:27
【问题描述】:

我想在 python 中对字符串列表进行排序,但是排序脚本应该省略这些字符串中包含的数字。可以在下面找到此类列表的示例:

list = ['aaa', '1aaa', 'abc', '2abc', '3abc', 'b2bb', 'b3bb']

我在 stackoverflow 上找到了一个主题,即this one,但这并没有回答我的问题。 经过更多研究,我发现了这个page,但我的实现不起作用:

import re 

def numbers_sort(file):
    lines = []
    lines += [line for line in open(file).readlines()]
    print(''.join(sorted(lines,  key=lambda key: [x for x in re.sub('^[-+]?[0-9]+$', '')])),end="")

我也一直在尝试使用 isdigit() 作为排序函数的键,但无济于事。

感谢您的帮助。

【问题讨论】:

    标签: python-3.x string list sorting digits


    【解决方案1】:

    key-Argument 需要一个函数,用于转换一个字符串。

    def numbers_sort(filename):
        with open(filename) as lines:
            print(''.join(sorted(lines,  key=lambda s: re.sub('[-+]?[0-9]+', '', s))), end="")
    

    【讨论】:

      猜你喜欢
      • 2017-04-07
      • 2013-07-02
      • 2022-11-25
      • 2016-05-10
      • 1970-01-01
      • 1970-01-01
      • 2018-07-02
      相关资源
      最近更新 更多