[Tutor] Iterating over two sequences in "parallel"
Rich Lovely
roadierich at googlemail.com
Sat Nov 28 18:33:58 CET 2009
2009/11/28 Wayne Werner <waynejwerner at gmail.com>:
>
>
> On Sat, Nov 28, 2009 at 6:59 AM, Dave Angel <davea at ieee.org> wrote:
>>
>> And if the lists are large, use itertools.izip() which works the same,
>> but produces an iterator.
>>
>> Note that if the lists are not the same length, I think it stops when the
>> shorter one ends.
>
> But you can use izip_longest:
> import itertools
> list1 = [1,2,3,4]
> list2 = [1,2]
> lIn [32]: for x, y in itertools.izip_longest(list1, list2):
> ....: print x,y
> ....:
> ....:
> 1 1
> 2 2
> 3 None
> 4 None
> HTH,
> Wayne
>
> --
> To be considered stupid and to be told so is more painful than being called
> gluttonous, mendacious, violent, lascivious, lazy, cowardly: every weakness,
> every vice, has found its defenders, its rhetoric, its ennoblement and
> exaltation, but stupidity hasn’t. - Primo Levi
>
> _______________________________________________
> Tutor maillist - Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>
You can also pass two lists to map:
>>> l1 = range(4)
>>> l2 = range(2)
>>> def p(x, y):
... print x, y
...
>>> map(p, l1, l2)
0 0
1 1
2 None
3 None
[None, None, None, None]
>>> def p(x, y):
... return (x or 0) + (y or 0)
...
>>> map(p, l1, l2)
[0, 2, 2, 3]
--
Rich "Roadie Rich" Lovely
There are 10 types of people in the world: those who know binary,
those who do not, and those who are off by one.
More information about the Tutor
mailing list