栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何正确排序带数字的字符串?

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

如何正确排序带数字的字符串?

也许您正在寻找人工排序(也称为自然排序):

import redef atoi(text):    return int(text) if text.isdigit() else textdef natural_keys(text):    '''    alist.sort(key=natural_keys) sorts in human order    http://nedbatchelder.com/blog/200712/human_sorting.html    (See Toothy's implementation in the comments)    '''    return [ atoi(c) for c in re.split(r'(d+)', text) ]alist=[    "something1",    "something12",    "something17",    "something2",    "something25",    "something29"]alist.sort(key=natural_keys)print(alist)

产量

['something1', 'something2', 'something12', 'something17', 'something25', 'something29']

PS。我已经更改了答案,以使用Toothy的自然排序实现(在此处发表评论),因为它比我的原始答案快得多。


如果您希望使用浮点数对文本进行排序,则需要将正则表达式从与整数(即

(d+)
)匹配的正则表达式更改为与浮点数匹配的正则表达式:

import redef atof(text):    try:        retval = float(text)    except ValueError:        retval = text    return retvaldef natural_keys(text):    '''    alist.sort(key=natural_keys) sorts in human order    http://nedbatchelder.com/blog/200712/human_sorting.html    (See Toothy's implementation in the comments)    float regex comes from https://stackoverflow.com/a/12643073/190597    '''    return [ atof(c) for c in re.split(r'[+-]?([0-9]+(?:[.][0-9]*)?|[.][0-9]+)', text) ]alist=[    "something1",    "something2",    "something1.0",    "something1.25",    "something1.105"]alist.sort(key=natural_keys)print(alist)

产量

['something1', 'something1.0', 'something1.105', 'something1.25', 'something2']


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/614114.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

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

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