关于正则表达式
从txt文件中读取关键字,关键字由字母和数字混合组成,先存放到一个集合中,然后转成列表对关键字进行排序,写入集合时一切正常,在转成列表进行排序时,程序报列表出界的错误。请教一下应该如何改正,谢谢!
keys = list(keys)
p = re.compile("(\d+)")
def my_cmp(v1, v2):
d1 = [int(i) for i in p.findall(v1)][0]
d2 = [int(i) for i in p.findall(v2)][0]
return cmp(d1, d2)
keys.sort(my_cmp)
[解决办法]
Python 2.7.3 (default, Apr 10 2012, 23:31:26) [MSC v.1500 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> import re
>>> exp = re.compile(r'(\d+)')
>>> keys = ['B0010','B0011','B0005','B0004','B0003','B0002','B0001','B0040','B0017','B0012','B0009','B0043','B0042','B0041','B0013','B0047','B0046','B0045','B0044','B0014',]
>>> print keys
['B0010', 'B0011', 'B0005', 'B0004', 'B0003', 'B0002', 'B0001', 'B0040', 'B0017', 'B0012', 'B0009', 'B0043', 'B0042', 'B0041', 'B0013', 'B0047', 'B0046', 'B0045', 'B0044', 'B0014']
>>> keys.sort(key=lambda x: int(exp.search(x).group(1)))
>>> print keys
['B0001', 'B0002', 'B0003', 'B0004', 'B0005', 'B0009', 'B0010', 'B0011', 'B0012', 'B0013', 'B0014', 'B0017', 'B0040', 'B0041', 'B0042', 'B0043', 'B0044', 'B0045', 'B0046', 'B0047']
>>>