Vectorization and Numeric (Newbie)
johnzenger at gmail.com
johnzenger at gmail.com
Tue Feb 28 11:21:12 EST 2006
"map" takes a function and a list, applies the function to each item in
a list, and returns the result list. For example:
>>> def f(x): return x + 4
>>> numbers = [4, 8, 15, 16, 23, 42]
>>> map(f, numbers)
[8, 12, 19, 20, 27, 46]
So, rather that ask if there is a different way to write f, I'd just
use f in a different way.
Another way to accomplish the same result is with a list comprehension:
>>> [f(x) for x in numbers]
[8, 12, 19, 20, 27, 46]
As you can see, if you wanted to "calculate all the values from 1 to
n," you could also use these techniques instead of a loop.
>>> n = 10
>>> [f(x) for x in xrange(1, n+1)]
[5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
More information about the Python-list
mailing list