【问题标题】:Python string numerical sorting with group [duplicate]带组的Python字符串数字排序[重复]
【发布时间】:2023-02-06 00:22:43
【问题描述】:

我想按数字对字符串进行排序,但将它们分组。意思是,将 Cs、Rs、... 放在一起,但按数字排序。


# input
a = ['C2', 'C1', 'R3', 'R21', 'C10', 'R1', 'L1']
# expected output
['C1', 'C2', 'C10', 'R1', 'R3', 'R21', 'L1']

# I tried multiple options, but didn't find the right one.
a.sort(key=lambda x: int(x[1:]))

那么如何在不创建特殊解析函数的情况下获取结果呢?

谢谢

【问题讨论】:

    标签: python


    【解决方案1】:

    您可以使用字母和数字的元组,而不仅仅是排序中的数字:

    >>> a.sort(key=lambda x: (x[0], int(x[1:])))
    ['C1', 'C2', 'C10', 'L1', 'R1', 'R3', 'R21']
    

    【讨论】:

    • 仅供参考,您不需要将 x[1:] 转换为 int,否则我会说同样的话
    猜你喜欢
    • 2018-04-20
    • 2012-04-16
    • 1970-01-01
    • 1970-01-01
    • 2018-02-16
    • 2019-12-13
    • 2017-11-17
    • 2021-01-25
    相关资源
    最近更新 更多