Map with an extra parameter
Peter Otten
__peter__ at web.de
Sat Sep 9 05:45:51 EDT 2006
ml1n wrote:
> I'm not really sure how to explain this so maybe some example code is
> best. This code makes a list of objects by taking a list of ints and
> combining them with a constant:
>
> class foo:
> def __init__(self):
> self.a = 0
> self.b = 0
>
> def func(a,b):
> f = new foo()
> f.a = a
> f.b = b
> return f
>
> constants = [1]*6
> vars = [1,2,3,4,5,6]
> objects = map(func,vars,constants)
>
> In the real world I need to do this as quick as possible (without
> resorting to c) and there are several constants. (The constant is only
> constant to each list so I can't make it a default argument to func.)
> My question is, can anyone think of a way to do this efficiently
> without having to use the `dummy` list of constants and would it be
> quicker?
Here are two more ways to achieve what you want, but you have to time them
youself.
>>> from itertools import starmap, izip, repeat
>>> class Foo:
... def __init__(self, a, b):
... self.a = a
... self.b = b
... def __repr__(self):
... return "Foo(a=%r, b=%r)" % (self.a, self.b)
...
>>> constants = repeat(1)
>>> vars = [1, 2, 3]
>>> list(starmap(Foo, izip(vars, constants)))
[Foo(a=1, b=1), Foo(a=2, b=1), Foo(a=3, b=1)]
This requires Python 2.5:
>>> from functools import partial
>>> map(partial(Foo, b=1), vars)
[Foo(a=1, b=1), Foo(a=2, b=1), Foo(a=3, b=1)]
Peter
More information about the Python-list
mailing list