Re: Vectorization and Numeric (Newbie)



"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]

.



Relevant Pages

  • Re: shouldnt list comprehension be faster than for loops?
    ... same as the difference between a for loop and a call to map. ... for a list comprehension, you'll see it's very similar to that generated ... if you need to create a Python function to pass to ...
    (comp.lang.python)
  • Re: Optimizing for fast floating-point numerical code
    ... I used mapping functions and `reduce' partly because they seemed like ... other hand, it hadn't occurred to me to use the loop macro, which is ... Map has to construct the target data structure - if the target is ... intrinsic function like `random' in a given Lisp implementation to be ...
    (comp.lang.lisp)
  • Re: How to build the => in a statement?
    ... You cannot embed a for loop in an argument list. ... a for loop and map are different beasts. ... to-possibly many transformation applied to the argument list and each ... push @args, $k, $hash; ...
    (comp.lang.perl.misc)
  • Re: Just wondering
    ... If the task is to test the overhead, then the two loops need to be equivalent. ... compare map() time to for time, ... def doit: ... Doing the loop tells what it takes to loop. ...
    (comp.lang.python)
  • Re: m//
    ... looping over array indices is bad style in Perl. ... a loop that looks like this ... I'm guessing that it first uses map to disable pattern metacharacters in ... containing the pattern to match: ...
    (comp.lang.perl.misc)