1

我正在尝试为 python 中的Look-and-Say序列编写一个正则表达式。这个想法是将给定的字符串拆分为相同数字的子字符串。经过反复试验,我有'((\d)\\2*)'.

对于这种模式,11244455221116[('11', '1'), ('2', '2'), ('444', '4'), ('55', '5'), ('22', '2'), ('111', '1'), ('6', '6')]符合预期。这有效,但看起来很笨拙。有没有更清洁的方法来做到这一点,有或没有正则表达式?

4

2 回答 2

1

您可以使用itertools.groupby

import itertools as IT

text = '11244455221116'
print([(''.join(group), key) for key, group in IT.groupby(text)])

产量

[('11', '1'), ('2', '2'), ('444', '4'), ('55', '5'), ('22', '2'), ('111', '1'), ('6', '6')]

但是re.findall更快:

In [67]: %timeit [(''.join(group), key)for key, group in IT.groupby(text*100)]
1000 loops, best of 3: 528 us per loop

In [68]: %timeit re.findall(r'((\d)\2*)', text*100)
1000 loops, best of 3: 219 us per loop
于 2013-07-25T21:57:18.630 回答
0

instead of splitting your string, you can do a replace with a lambda function:

re.sub(r'(\d)\1*', lambda x: str(len(x.group(0)))+x.group(1), '112224355')

result: 2132141325

于 2013-07-25T22:33:19.670 回答