map
Bengt Richter
bokr at oz.net
Fri Jun 7 17:23:54 EDT 2002
On Fri, 7 Jun 2002 14:33:45 -0400, "Michael Weiss" <FooWeissBarMike at hotmail.com> wrote:
>Would this work?
>
Yes, after
>>> from math import pow
;-)
>##########
>x = [1,2,3,4]
>y = 2
>
>#this?
>print map(lambda z: pow(z,y), x)
Why not just show that it does work ;-)
>>> print map(lambda z: pow(z,y), x)
[1.0, 4.0, 9.0, 16.0]
>
># or this?
>print map(pow, x, [y for z in xrange(len(x))])
ditto ;-)
>>> print map(pow, x, [y for z in xrange(len(x))])
[1.0, 4.0, 9.0, 16.0]
or just
>>> map(pow, x, [y]*len(x))
[1.0, 4.0, 9.0, 16.0]
>##########
>
math.pow might not be optimal for speed (or accuracy for e.g., 3L**100),
depending on arguments. If y is integer 2 or 3 for example,
code for x**y is probably pretty fast. (I am speculating
that the BINARY_POWER byte code opeator is optimized for
some special cases).
If y is fixed for the run through x, but you don't know it
beforehand, you could generate a lambda on the fly with a constant
built into the code with one eval and pass that to map, e.g.,
>>> x = [1,2,3,4]
>>> y=2
>>> map(eval('lambda x: x**%s' % y), x)
[1, 4, 9, 16]
>>>
>>> import dis
>>> dis.dis(eval('lambda x: x**%s' % y))
0 SET_LINENO 1
3 LOAD_FAST 0 (x)
6 LOAD_CONST 1 (2) <<-- note constant from y
9 BINARY_POWER
10 RETURN_VALUE
>>>
>>> x=map(float,x); x
[1.0, 2.0, 3.0, 4.0]
>>> y=2.0
>>> map(eval('lambda x: x**%s' % y), x)
[1.0, 4.0, 9.0, 16.0]
>>> dis.dis(eval('lambda x: x**%s' % y))
0 SET_LINENO 1
3 LOAD_FAST 0 (x)
6 LOAD_CONST 1 (2.0) <<-- note constant from y
9 BINARY_POWER
10 RETURN_VALUE
also note that the eval can effectively fold constant-valued expressions:
>>> x=range(1,5); x; y=2; y
[1, 2, 3, 4]
2
>>> map(eval('lambda x: x**%s' % (1.0/y)), x)
[1.0, 1.4142135623730951, 1.7320508075688772, 2.0]
>>> dis.dis(eval('lambda x: x**%s' % (1.0/y)))
0 SET_LINENO 1
3 LOAD_FAST 0 (x)
6 LOAD_CONST 1 (0.5) <<-- note constant from 1.0/y
9 BINARY_POWER
10 RETURN_VALUE
I suppose you could look at the eval('lambda ... as a kind of currying.
>"Giorgi Lekishvili" <gleki at gol.ge> wrote in message
>news:3D007666.2B6D3582 at gol.ge...
>> Hi all!
>>
>> Is there a way to map a function with several arguments to a list? E.g.,
>>
>> >>>import math
>> >>>import MLab
>> >>>a=MLab.rand(3,5)
>> >>>b=map(math.pow,a)
>>
>> of course, this doesn't work.
>>
>> What to do? My task is to optimize the power (i.e., y in pow(x,y)) to
>> achieve maximal performance.
Need more info about x and y for that ;-)
Regards,
Bengt Richter
More information about the Python-list
mailing list