for loop question

George Sakkis george.sakkis at gmail.com
Wed Oct 10 16:50:41 EDT 2007


On Oct 10, 4:12 pm, Tim Chase <python.l... at tim.thechases.com> wrote:

> > test = u"Hello World"
>
> > for cur,next in test:
> >     print cur,next
>
> > Ideally, this would output:
>
> > 'H', 'e'
> > 'e', 'l'
> > 'l', 'l'
> > 'l', 'o'
> > etc...
>
> > Of course, the for loop above isn't valid at all. I am just giving an
> > example of what I'm trying to accomplish. Anyone know how I can achieve the
> > goal in the example above? Thanks.
>
> A "works-for-me":
>
>  >>> pairs = (test[i:i+2] for i in xrange(len(test)-1))
>  >>> for a,b in pairs:
> ...     print a,b
> ...
> H e
> e l
> l l
> l o
> o
>    w
> w o
> o r
> r l
> l d
>  >>>
>
> -tkc

Or generalized for arbitrary iterables, number of items at a time,
combination function and stopping criterion:

from itertools import islice, takewhile, repeat

def taking(iterable, n, combine=tuple, pred=bool):
    iterable = iter(iterable)
    return takewhile(pred, (combine(islice(iterable,n)) for _ in
repeat(0)))

>>> for p in taking(test,2): print p

(u'H', u'e')
(u'l', u'l')
(u'o', u' ')
(u'W', u'o')
(u'r', u'l')
(u'd',)

>>> for p in taking(test,2, combine=''.join): print p

He
ll
o
Wo
rl
d


George




More information about the Python-list mailing list