Iteration over two sequences

Paul McGuire ptmcg at austin.rr._bogus_.com
Wed Jan 12 11:04:28 EST 2005


"Henrik Holm" <news+0409 at henrikholm.com> wrote in message
news:1gq9qs9.3snutr1s4mcn2N%news+0409 at henrikholm.com...
> I am just starting to learn Python, mostly by going through the examples
> in Dive Into Python and by playing around.
>
> Quite frequently, I find the need to iterate over two sequences at the
> same time, and I have a bit of a hard time finding a way to do this in a
> "pythonic" fashion.  One example is a dot product.  The straight-ahead
> C-like way of doing it would be:
>
> def dotproduct(a, b):
>     psum = 0
>     for i in range(len(a)):
>         psum += a[i]*b[i]
>     return psum
>
> However, the range(len(a)) term is awfully un-pythonic :)
> The built-in function map() gives me a way of "transposing" the a list
> and the b list, and  now I can handle it with a list comprehension:
>
> def dotproduct(a, b):
>     return sum([x*y for x, y in map(None, a, b)])
>
> My concern is one of efficiency: it seems to me that I have two loops
> there: first one implied with map(...) and then the for loop -- which
> seems like a waste since I feel I should be able to do the
> multiplication via an argument to map.  So far I have come up with an
> alternative via defining a separate function:
>
> def dotproduct(a, b):
>     def prod(x,y): return x*y
>     return sum(map(prod, a, b))
>
> I suppose I could also use a lambda here -- but is there a different,
> efficient, and obvious solution that I'm overlooking?
>
>
> Thanks,
> Henrik
>
> -- 
> "On some great and glorious day the plain folks of the land will reach
> in their heart's desire at last and the White House will be adorned by
> a downright moron."
>                              -H.L. Mencken (1880-1956) American Writer

zip maybe?

def dotproduct(a,b):
    return sum([x*y for x,y in zip(a,b)])

-- Paul





More information about the Python-list mailing list