from itertools import groupby
from functools import reduce
a = [1,2,3,4,5,6,7,8,9,]
def pipe(data, *process):
result = data
for proce in process:
result = proce(result)
return result
p = pipe(a, lambda x: map(lambda y:y**2, x),
lambda x: sorted(x, key=lambda y: y%2),
lambda x: groupby(x, key=lambda y: y%2),)
for g, d in p:
l = list(d)
s = sum(l)
print("{g}: {d}, sum:{s}".format(g=g, d=l, s=s))
class groupby:
# [k for k, g in groupby('AAAABBBCCDAABBB')] --> A B C D A B
# [list(g) for k, g in groupby('AAAABBBCCD')] --> AAAA BBB CC D
def __init__(self, iterable, key=None):
if key is None:
key = lambda x: x
self.keyfunc = key
self.it = iter(iterable)
self.tgtkey = self.currkey = self.currvalue = object()
def __iter__(self):
return self
def __next__(self):
self.id = object()
while self.currkey == self.tgtkey:
self.currvalue = next(self.it) # Exit on StopIteration
self.currkey = self.keyfunc(self.currvalue)
self.tgtkey = self.currkey
return (self.currkey, self._grouper(self.tgtkey, self.id))
def _grouper(self, tgtkey, id):
while self.id is id and self.currkey == tgtkey:
yield self.currvalue
try:
self.currvalue = next(self.it)
except StopIteration:
return
self.currkey = self.keyfunc(self.currvalue)