如何正确排序里面有数字的字符串? [复制]

2023-12-13

我有一个包含数字的字符串列表,但我找不到对它们进行排序的好方法。
例如我得到这样的东西:

something1
something12
something17
something2
something25
something29

sort() method.

我知道我可能需要以某种方式提取数字,然后对列表进行排序,但我不知道如何以最简单的方式做到这一点。


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

import re

def atoi(text):
    return int(text) if text.isdigit() else text

def 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)

yields

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

附言。我已经更改了我的答案,以使用 Toothy 的自然排序实现(发布在评论中)here)因为它比我原来的答案要快得多。


如果您希望使用浮点数对文本进行排序,那么您需要将正则表达式从与整数匹配的正则表达式(即(\d+)) to 匹配浮点数的正则表达式:

import re

def atof(text):
    try:
        retval = float(text)
    except ValueError:
        retval = text
    return retval

def 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)

yields

['something1', 'something1.0', 'something1.105', 'something1.25', 'something2']
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何正确排序里面有数字的字符串? [复制] 的相关文章

随机推荐