python中的排序列表


问题内容

如果我有一个字符串列表,例如,["a143.txt", "a9.txt", ]如何按列表中的数字而不是字符串按升序对其进行排序。即我想从此"a9.txt"出现。"a143.txt"``9 < 143

谢谢。


问题答案:

它称为“自然排序顺序”,来自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 )