【问题标题】:How to sort the list in Python? [duplicate]如何在 Python 中对列表进行排序? [复制]
【发布时间】:2013-12-06 14:01:10
【问题描述】:

我正在尝试按升序对 Python 中的列表进行排序。

下面是我的代码 -

children=zk.get_children("/my/example", watch=my_func)
print(children)

所以上面的打印语句会打印出这样的东西——

[u'test2', u'test1', u'test3']

or

[u'test3', u'test2', u'test1']

或以任何顺序..

现在我需要确保在排序后它应该按照升序排列

[u'test1', u'test2', u'test3']

有什么想法可以在 Python 中有效地完成吗?

注意:名称始终以test 开头,然后是some number

【问题讨论】:

  • 字典顺序还是数字顺序?
  • 你试过什么?您是否阅读过list.sortsorted 上的文档?

标签: python list sorting


【解决方案1】:

你需要的是自然排序:

import re

convert = lambda text: int(text) if text.isdigit() else text.lower() 
alphanum_key = lambda key: [ convert(c) for c in re.split('([0-9]+)', key) ] 

def natural_sort(l): 
    return sorted(l, key=alphanum_key)

然后你做

lst.sort(key=natural_sort)

如果你想反转它,那么添加reverse=True 参数。如果您不想就地排序(但要创建一个新列表),请改用sorted(lst, key=natural_sort)

【讨论】:

    【解决方案2】:

    假设您想按测试编号对数组进行排序,您只需传递 sorted 一个 key 函数,该函数将提取每个 'test' 末尾的数字:

    >>> tests = [ "test%s" % i for i in range(1, 15) ]
    >>> sorted(tests, key=lambda t: int(t[4:]))
    ['test1', 'test2', 'test3', 'test4', 'test5', 'test6', 'test7', 'test8',
     'test9', 'test10', 'test11', 'test12', 'test13', 'test14']
    

    【讨论】:

      【解决方案3】:

      试试sorted()函数:

      >>> sortedList = sorted([u'test3',u'test2',u'test5'])
      >>> print sortedList
      [u'test2', u'test3', u'test5']
      

      【讨论】:

        猜你喜欢
        • 2018-07-21
        • 1970-01-01
        • 2016-10-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-02-10
        • 2021-10-28
        • 2016-02-26
        相关资源
        最近更新 更多