Python字母和数字的混合时按照数字排序

Python字母和数字的混合时按照数字排序

在实际工作中经常会遇到需要将带有字母和数字的字符串进行混合排序,在Python中并没有这种类似的参数,所以需要自己进行设置。

import re

# 将可以转化为数字的转化为数字
# 不可以转化的保留原始类型
def tryint(s):
    try:
        return int(s)
    except ValueError:
        return s
    # 也可以使用
    # return int(s) if s.isdigit() else s

# 将字母和数字分开
def alphanum_key(s):
    """ Turn a string into a list of string and number chunks.
        "z23a" -> ["z", 23, "a"]
    """
    return [ tryint(c) for c in re.split('([0-9]+)', s) ]

def sort_nicely(l):
    """ Sort the given list in the way that humans expect.
    """
    # 使用alphanum_key作为key进行排序
    l.sort(key=alphanum_key)

具体实现:

alist=[
    "ls1",
    "ls12",
    "ls17",
    "ls2",
    "ls25",
    "lsM"]
alist.sort(key=alphanum_key)

# 输出:
['ls1',
 'ls2',
 'ls12',
 'ls17',
 'ls25',
 'lsM']
posted @ 2022-06-19 09:53  XYSGIS  阅读(267)  评论(0)    收藏  举报