need help on generator...
__peter__ at web.de
Fri Jan 21 16:36:28 CET 2005
> i'm trying to understand how i could build following consecutive sets
> from a root one using generator :
> l = [1,2,3,4]
> would like to produce :
> [1,2], [2,3], [3,4], [1,2,3], [2,3,4]
> but unfortunately can not, i guess i can do it by using sub generator
> and maybe enumerate, please if you help could you explain a bit the
> trick ? looks like this sub generator thing mess me up.
Here is an (untested) variant that accepts any iterable while trying to
remain memory-efficient. This makes it necessary to shuffle the order of
the output a bit.
from itertools import tee, islice
def gen(iterable, start, end):
it = iter(iterable)
it, a = tee(it)
a = tuple(islice(a, end-1))
for sz in xrange(start, len(a)+1):
if __name__ == "__main__":
print list(gen(range(1, 5), 2, 4))
# [(1, 2), (1, 2, 3), (2, 3), (2, 3, 4), (3, 4)]
More information about the Python-list