need help on generator...

Denis S. Otkidach ods at strana.ru
Fri Jan 21 09:14:28 EST 2005


On 21 Jan 2005 05:58:03 -0800
joh12005 at yahoo.fr (Joh) wrote:

> 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] 

>>> def consecutive_sets(l):
...     for i in xrange(2, len(l)):
...         for j in xrange(0, len(l)-i+1):
...             yield l[j:j+i]
... 
>>> list(consecutive_sets([1,2,3,4]))
[[1, 2], [2, 3], [3, 4], [1, 2, 3], [2, 3, 4]]

-- 
Denis S. Otkidach
http://www.python.ru/      [ru]



More information about the Python-list mailing list