Python排序字​​符串以数字开头

时间:2012-06-02 22:03:22

标签: 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 = r.match(s)
    return m.group(0)

x.sort(key=sort_by_number)

但有些字符串没有数字,这会导致错误。 感谢。

3 个答案:

答案 0 :(得分:4)

答案 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)

关键是如果不匹配,则返回字符串