如果我有一个字符串列表,例如["a143.txt", "a9.txt", ]
我如何按列表中的数字按升序排序,而不是按字符串排序.即我要"a9.txt"
出庭"a143.txt"
,因为9 < 143
.
谢谢.
wmi*_*mil 13
它被称为"自然排序",来自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 )
Run Code Online (Sandbox Code Playgroud)