Ree Ray Ree Ray - 5 months ago 10
Python Question

How to pass multiple params in Fn when I using Python map(Fn, Iterable)?

As for

map(Fn, Iterable)
, my
Fn()
is fllowing:

def Fn(x, k):
return x+k


But, if I want to use the
Fn()
in
map()
, the code could not like this:

map(Fn(Iterable, k), Iterable)


It means that how can I do if I want to use the param
k
? THX!

Answer

Here are some possibilities

def fn(x,k):
   return x+k 

In [1095]: k=10  # in global space

In [1096]: map(lambda x: fn(x,k), [1,2,3])
Out[1096]: <map at 0xb263e04c>   # ops, py3, need

In [1097]: list(map(lambda x: fn(x,k), [1,2,3]))
Out[1097]: [11, 12, 13]

I prefer list comprehensions to map:

In [1100]: [(lambda x: fn(x,k))(x) for x in [1,2,3]]
Out[1100]: [11, 12, 13]

In [1101]: [fn(x,k) for x in [1,2,3]]
Out[1101]: [11, 12, 13]

or if both x and k come from iterables, we can join them with zip:

In [1102]: [fn(x,k) for x,k in zip([1,2,3],[10,20,30])]
Out[1102]: [11, 22, 33]

I was going to suggest functools.partial, but I don't think I can use that with the 2nd positional argument. I can use it to partially define the 1st argument (in this case it doesn't matter).

In [1107]: from functools import partial

In [1111]: [partial(fn, 1)(k) for k in [10,20,30]]
Out[1111]: [11, 21, 31]

In [1112]: list(map(partial(fn, 1),[10,20,30]))
Out[1112]: [11, 21, 31]

If I change fn so k becomes a keyword argument

def fn(x,k=0):
    return x+k

In [1114]: [partial(fn, k=10)(x) for x in [1,2,3]]
Out[1114]: [11, 12, 13]

And similarly for map.

If I define fn so it takes a tuple, I could use zip with map:

def fn(args):
   x,k=args
   return x+k

In [1117]: list(map(fn,zip([1,2,3],[10,20,30])))
Out[1117]: [11, 22, 33]
Comments