fork download
  1. from collections import deque
  2.  
  3. class splitby:
  4. # [''.join(s) for s in splitby('AAAABBBCCDAABBB', operator.eq)] --> ['AAAA', 'BBB', 'CC', 'D', 'AA', 'BBB']
  5. def __init__(self, iterable, splitter):
  6. self.splitfunc = splitter
  7. self.it = iter(iterable)
  8. self.segment = None
  9. def __iter__(self):
  10. return self
  11. def __next__(self):
  12. if self.segment:
  13. deque(self.segment, maxlen=0)
  14. if self.segment is None:
  15. raise StopIteration
  16. else:
  17. self.curvalue = next(self.it)
  18. self.segment = self._splitter()
  19. return self.segment
  20. def _splitter(self):
  21. split = False
  22. while not split:
  23. yield self.curvalue
  24. prev = self.curvalue
  25. try:
  26. self.curvalue = next(self.it)
  27. except StopIteration:
  28. self.segment = None
  29. return
  30. split = self.splitfunc(prev, self.curvalue)
  31.  
  32. from operator import gt
  33. x = [1, 2, 3, 4, 1, 2, 3, 1, 2, 1]
  34. print([list(s) for s in splitby(x, gt)])
Success #stdin #stdout 0.02s 28376KB
stdin
Standard input is empty
stdout
[[1, 2, 3, 4], [1, 2, 3], [1, 2], [1]]