Python3中列表的自然排序

2024-04-29 09:03:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试对列表进行排序:

[
    '[fc] EDW Ratio (10 degrees)', 
    ' [fc] EDW Ratio (45 degrees)', 
    ' [fc] EDW Ratio (60 degrees)', 
    ' [fc] EDW Ratio (25 degrees)', 
    ' [fc] EDW Ratio (20 degrees)', 
    ' [fc] EDW Ratio (30 degrees)', 
    ' [fc] EDW Ratio (15 degrees)', 
    ' [fc] EDW output factor (60 degrees)', 
    ' [fc] Quality index'
]

使用接受答案的第一部分here

但名单最终是这样的:

[
    ' [fc] EDW Ratio (15 degrees)', 
    ' [fc] EDW Ratio (20 degrees)', 
    ' [fc] EDW Ratio (25 degrees)', 
    ' [fc] EDW Ratio (30 degrees)', 
    ' [fc] EDW Ratio (45 degrees)', 
    ' [fc] EDW Ratio (60 degrees)', 
    ' [fc] EDW output factor (60 degrees)', 
    ' [fc] Quality index', 
    '[fc] EDW Ratio (10 degrees)'
]

然而,我希望EDW Ratio(10度)在排序后结束于列表的开头(索引位置0)。你知道吗

如何做到这一点?你知道吗

我的代码包括:

#
# Method to define natural sorting used to sort lists
#
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) ]

    .
    .
    .


    tname_list = test_names.split(",") # this outputs the exact first (unsorted) list shown above

    tname_list.sort(key=natural_keys) # use human sorting defined above. This outputs the second list shown above.

Tags: thetextin列表keysnaturalsortedw
3条回答

您的代码是正确的,但是您的数据看起来不正确:所有条目都有一个前导空格,这意味着它们“在”您标识为最少的条目之前,实际上没有前导空格。你知道吗

如果数据没有问题,我建议您修改代码以忽略前导空格(检查:How do I remove leading whitespace in Python?)。你知道吗

如果您的任何字符串包含多个数字,或者将这些数字放在字符串的开头或结尾,您将遇到麻烦。这是因为Python无法将intstr进行比较。键函数应该以元组或列表的形式返回。你知道吗

def atoi(text):
    return (int(text), '') if text.isdigit() else (math.nan, text)

math.nan是特殊的,因为它永远不会比实际数字小。你知道吗

您需要修改natural_keys,以便只将字符串的数字部分作为int返回。转换时应该使用int(),而不是返回字符的ascii码的atoi()。你知道吗

相关问题 更多 >