【问题标题】:How to do a natural sort on a complex list in Python3?如何在 Python3 中对复杂列表进行自然排序?
【发布时间】:2019-10-03 14:55:18
【问题描述】:

我可以对简单列表进行自然排序,也可以对复杂列表中的特定键进行正常排序。我需要对复杂列表中的键进行自然排序。

鉴于这个程序:

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",
    "something10.0",
    "something1.25",
    "something1.105"]

alist.sort(key=natural_keys)
print("alist:")
for i in alist: print(i)

from operator import itemgetter

blist=[
    ['a', "something1"],
    ['b', "something2"],
    ['c', "something10.0"],
    ['d', "something1.25"],
    ['e', "something1.105"]]

blist.sort(key=itemgetter(1))
print("\nblist:")
for i in blist: print(i[1])

我得到了这些结果:

alist:
something1
something1.105
something1.25
something2
something10.0

blist:
something1
something1.105
something1.25
something10.0
something2

如何让 blist 和 alist 一样排序?

【问题讨论】:

    标签: python python-3.x sorting natural-sort


    【解决方案1】:

    您可以使用lambda 代替itemgetter

    blist.sort(key=lambda x: natural_keys(x[1]))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-08-05
      • 1970-01-01
      • 2019-06-25
      • 1970-01-01
      • 2021-09-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多