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

时间:2011-05-11 16:21:41

标签: python regex sorting string

  

可能重复:
  Does Python have a built in function for string natural sort?

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

something1
something12
something17
something2
something25
something29

使用sort()方法。

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

1 个答案:

答案 0 :(得分:177)

也许您正在寻找human sorting(也称为natural sorting):

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)

产量

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

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


如果您希望使用浮点数对文本进行排序,则需要将正则表达式从匹配整数(即(\d+))更改为a regex that matches floats

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)

产量

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