Skip to content

Commit 0f9d8ab

Browse files
timfelcosminbasca
authored andcommitted
add itertools.compress
1 parent e4ae70c commit 0f9d8ab

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

graalpython/lib-graalpython/itertools.py

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -736,3 +736,34 @@ def __next__(self):
736736
else:
737737
self.saved.append(obj)
738738
return obj
739+
740+
741+
class compress():
742+
"""Make an iterator that filters elements from *data* returning
743+
only those that have a corresponding element in *selectors* that evaluates to
744+
``True``. Stops when either the *data* or *selectors* iterables has been
745+
exhausted.
746+
Equivalent to::
747+
748+
def compress(data, selectors):
749+
# compress('ABCDEF', [1,0,1,0,1,1]) --> A C E F
750+
return (d for d, s in zip(data, selectors) if s)
751+
"""
752+
def __init__(self, data, selectors):
753+
self.data = iter(data)
754+
self.selectors = iter(selectors)
755+
756+
def __iter__(self):
757+
return self
758+
759+
def __next__(self):
760+
# No need to check for StopIteration since either data or selectors will
761+
# raise this. The shortest one stops first.
762+
while True:
763+
next_item = next(self.data)
764+
next_selector = next(selectors)
765+
if next_selector:
766+
return next_item
767+
768+
def __reduce__(self):
769+
return (type(self), (self.data, self.selectors))

0 commit comments

Comments
 (0)