栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

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

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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']
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/926039.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号