I am implementing a local optimization that fuses objects together. In the simplest form, given a list:
[0, 3, 5, 8, 1, 2, 9, 0, 3, 5]
I would like to group into:
[[0, 3], 5, 8, 1, 2, 9, [0, 3], 5]
which is based on a provided criterion:
def is_group(a, b):
return a == 0 and b == 3
My current solution seems a bit convoluted, and am looking for most pythonic approach:
def pairwise(iterable):
for (a, b) in zip(iterable, iterable[1:]):
yield (a, b)
yield (iterable[-1], None) # handle edge case
def fuse(ops):
ops_new = []
skip_next = False
for (a, b) in pairwise(ops):
if is_group(a, b):
ops_new.append([a, b])
skip_next = True
elif skip_next:
skip_next = False
elif:
ops_new.append(a)
I've looked at groupby, which is the closest but aren't quite sure how to make it work since here the criterion depends on pairwise arguments.
Edit: Another way to ask the question is I am basically trying to do pattern search and replace with lists (e.g. regex for lists).
pairwise? IOW, why do you need to consider the last element againstNone?(0, 3), (3, 5), (5, 8), ..., (3, 5). My fuse operation never appendsb, so my result would always be missing the last element.from itertools import zip_longest, isliceThen simplyzip_longest(x, islice(x, 1, None))instead of yourpairwise