如何在python中按Number然后字母对列表进行排序?

时间:2015-06-25 03:11:16

标签: python string sorting

有没有办法按数字和字母对列表进行排序?

alist = [ "1", "A12", "12", "B12", "A17", "2", "25", "29", "122", "A1" , "3", "17"]

我想回复:

['1', 'A1', '2', '3', '12', 'A12', 'B12', '17', 'A17', '25', '29', '122']

2 个答案:

答案 0 :(得分:4)

有点奇怪,但好吧......

import re

def sorter(s):
     match = re.search('([a-zA-Z]*)(\d+)', s)
     return int(match.group(2)), match.group(1)

sorted(alist, key=sorter)
Out[13]: ['1', 'A1', '2', '3', '12', 'A12', 'B12', '17', 'A17', '25', '29', '122']

答案 1 :(得分:0)

sorted(alist, key=lambda x: (int(re.search(r'(\d+)', x).group()), x))