Elegent way to collapse or expand sub-sequences of a list in Python?

Posted by forgot on Stack Overflow See other posts from Stack Overflow or by forgot
Published on 2010-04-20T11:32:43Z Indexed on 2010/04/20 11:53 UTC
Read the original article Hit count: 213

Filed under:
|
|
|
|

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.

© Stack Overflow or respective owner

Related posts about python

Related posts about compiler