You could just write a simple class to encapsulate the temp variables, then use a method of that class as the key function:
class KeyClass(object):
def __init__(self):
self.lastValue = None
self.currentKey = 1
def handleVal(self, val):
if self.lastValue is not None and abs(val - self.lastValue) > 100:
self.currentKey += 1
self.lastValue = val
return self.currentKey
>>> [(k, list(g)) for k, g in itertools.groupby(data, KeyClass().handleVal)]
[(1, [1, 2, 100, 105]), (2, [300, 350, 375]), (3, [500]), (4, [800, 808])]
Just for fun, I also came up with this rather mind-bending way to do it by using the send
method of a pre-advanced generator as the key function:
def keyGen():
curKey = 1
newVal = yield None
while True:
oldVal, newVal = newVal, (yield curKey)
if oldVal is None or abs(newVal-oldVal) > 100:
curKey += 1
key = keyGen()
next(key)
>>> [(k, list(g)) for k, g in itertools.groupby(data, key.send)]
[(1, [1, 2, 100, 105]), (2, [300, 350, 375]), (3, [500]), (4, [800, 808])]
Wrapping your head around that may be a good exercise in understanding .send
(it was for me!).