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 に答える