Elegent way to collapse or expand sub-sequences of a list in Python?
- by forgot
I want to collapse or expand sub-sequences of a list
e.g. ['A', 'B', 'D', 'E', 'H'] -> ['AB', 'DE', 'H'] and vice versa
currently I wrote some ugly code like:
while True:
for i, x in enumerate(s):
if x == 'A' and s[i+1] == 'B':
s[i:i+2] = 'AB'
break
else:
break
For people who asking 'why do that thing':
Actually I'm working on a optimizing compiler and this is the peephole part.
Writing pattern matching is a little annoying.