我有下一个列表:
a = ['1th Word', 'Another Word', '10th Word']
print a.sort()
>>> ['10th Word', '1th Word', 'Another Word']
但我需要:
^{2}$有没有一个简单的方法可以做到这一点?在
我试过了:
r = re.compile(r'(\d+)')
def sort_by_number(s):
m = r.match(s)
return m.group(0)
x.sort(key=sort_by_number)
但是有些字符串没有数字,这会导致错误。 谢谢。在
这通常被称为“自然分类”。在
请参见Does Python have a built in function for string natural sort?和Python analog of natsort function (sort a list using a "natural order" algorithm);也可参见http://code.activestate.com/recipes/285264-natural-string-sorting/和{a4}。在
这是一个适用于一般情况的函数
结果:
^{pr2}$关键是如果不匹配,则按原样返回字符串
相关问题 更多 >
编程相关推荐