我有下一个清单:
a = ['1th Word', 'Another Word', '10th Word']
print a.sort()
>>> ['10th Word', '1th Word', 'Another Word']
但我需要:
['1th Word', '10th Word','Another Word']
有一种简单的方法吗?
我试过了:
r = re.compile(r'(\d+)')
def sort_by_number(s):
m = r.match(s)
return m.group(0)
x.sort(key=sort_by_number)
但有些字符串没有数字,这会导致错误。 感谢。
答案 0 :(得分:4)
这通常被称为“自然排序”。
见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/和http://www.codinghorror.com/blog/2007/12/sorting-for-humans-natural-sort-order.html。
答案 1 :(得分:4)
这是一个适用于一般情况的函数
import re
def natkey(s):
return [int(p) if p else q for p, q in re.findall(r'(\d+)|(\D+)', s)]
x = ['1th Word', 'Another Word 2x', 'Another Word 20x', '10th Word 10', '2nd Word']
print sorted(x)
print sorted(x, key=natkey)
结果:
['10th Word 10', '1th Word', '2nd Word', 'Another Word 20x', 'Another Word 2x']
['1th Word', '2nd Word', '10th Word 10', 'Another Word 2x', 'Another Word 20x']
答案 2 :(得分:1)
r = re.compile(r'(\d+)')
def sort_by_number(s):
m = r.match(s)
return m and m.group(0) or s
x.sort(key=sort_by_number)
关键是如果不匹配,则返回字符串