【问题标题】:How to sort alphanumeric values in Python? [duplicate]如何在 Python 中对字母数字值进行排序? [复制]
【发布时间】:2019-07-01 23:54:19
【问题描述】:

我目前正在构建一个程序,并且想知道如何根据从小到大的数字对如下所示的字母数字列表进行排序。

array1 = ["14f","9c","2d","7a"]

我只希望数字像这样排序 ["2d","7a","9c","14f"]

感谢任何帮助。

【问题讨论】:

  • 您可以通过将每个字符串转换为其十六进制值将其转换为数字列表,然后对数字列表进行排序是一个众所周知的问题。
  • 这是一个十六进制值吗?即如果列表是['1ff', '2a'],那么哪个排在第一位?

标签: python arrays python-3.x python-2.7 list


【解决方案1】:

您可以使用 sorted 和自定义 key 函数来对列表进行排序:

import re
sorted(array1, key = lambda x: int(re.search(r'\d+', x)[0]))
# ['2d', '7a', '9c', '14f']

这个自定义的key 函数使用re.search 提取每个字符串中的数字:

[int(re.search(r'\d+', i)[0]) for i in array1] 
# [14, 9, 2, 7]

【讨论】:

    猜你喜欢
    • 2023-03-06
    • 1970-01-01
    • 2015-10-14
    • 1970-01-01
    • 2013-10-22
    • 2018-04-09
    • 2020-08-07
    • 1970-01-01
    • 2018-02-09
    相关资源
    最近更新 更多