Python排序字符串以数字开头
我有下一个清单:Python排序字符串以数字开头,python,Python,我有下一个清单: 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
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)
但是有些字符串没有数字,这会导致错误。
谢谢。这通常被称为“自然排序”
见和;还有
关键是如果不匹配,则按原样返回字符串
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']
['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']