0

我有下一个清单:

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)

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

4

3 回答 3

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']
于 2012-06-02T22:20:19.690 回答
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)

关键是如果没有匹配,则按原样返回字符串

于 2012-06-02T22:13:08.837 回答