substituting list comprehensions for map()
Steven D'Aprano
steven at REMOVE.THIS.cybersource.com.au
Tue Nov 3 20:53:15 EST 2009
On Tue, 03 Nov 2009 10:22:28 -0500, J Kenneth King wrote:
> However in this case the procedure by which we derive the value is not
> important or even interesting. It is much more succinct to think of the
> operation as a value and express it accordingly. There's no need to
> clutter the mind with extra name bindings and iteration keywords. They
> won't make our idea any more clear.
>
> dot_product = map(mul, vec1, vec2)
>
> vs
>
> dot_product = [a * b for a, b in zip(vec1, vec2)]
>
> It's very clear, at least to me, what a dot-product is in this case.
Except it's not.
The dot product of two vectors returns a scalar, not another vector:
http://en.wikipedia.org/wiki/Dot_product
So what you want is:
dot_product = sum(map(mul, vec1, vec2))
> Adding in the loop construct and name bindings doesn't enhance my
> understanding of what a dot-product is. I don't need to see the loop
> construct at all in this case. A dot product is simply the
> multiplication of each element in a vector sequence.
What you need is to define a function dot-product, and not hijack the
name for a local value. Then the function's implementation is irrelevant
to you: it could use a list comp, or could use map, it could use a for-
loop, a while loop, recursion, or black magic:
scalar = dot_product(vec1, vec2)
--
Steven
More information about the Python-list
mailing list