python中的排序列表 [英] sorting list in python
本文介绍了python中的排序列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我有字符串列表,例如["a143.txt", "a9.txt", ]
如何按列表中的数字而不是字符串按升序对其进行排序. IE.自9 < 143
以来,我希望"a9.txt"
出现在"a143.txt"
之前.
if I have a list of strings e.g. ["a143.txt", "a9.txt", ]
how can I sort it in ascending order by the numbers in the list, rather than by the string. I.e. I want "a9.txt"
to appear before "a143.txt"
since 9 < 143
.
谢谢.
推荐答案
它称为自然排序顺序", 来自 http://www.codinghorror.com/blog/2007 /12/sorting-for-humans-natural-sort-order.html
It's called "natural sort order", From http://www.codinghorror.com/blog/2007/12/sorting-for-humans-natural-sort-order.html
尝试一下:
import re
def sort_nicely( l ):
""" Sort the given list in the way that humans expect.
"""
convert = lambda text: int(text) if text.isdigit() else text
alphanum_key = lambda key: [ convert(c) for c in re.split('([0-9]+)', key) ]
l.sort( key=alphanum_key )
这篇关于python中的排序列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文