Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Applying map for partial argument

Given the following function f with two arguments, what is the standard way to apply map to only x?

def f (x,y):
    print x,y

More specifically, I would like to perform the following operation with map in one line.

list=[1,2,3]
fixed=10
for s in list:
    f(s,fixed)

One way to do so is:

import functools
map(functools.partial(lambda x,y:f(y,x),fixed),list)

What is a better way?

like image 414
Alfad Avatar asked Apr 25 '12 11:04

Alfad


People also ask

Can Map function have more than 2 arguments?

Passing Multiple Arguments to map() function Suppose we pass n iterable to map(), then the given function should have n number of arguments. These iterable arguments must be applied on given function in parallel. In multiple iterable arguments, when shortest iterable is drained, the map iterator will stop.

Can map take multiple arguments?

Using the Python map() function with multiple arguments functions. Besides using the Python map() function to apply single argument functions to an iterable, we can use it to apply functions with multiple arguments.

How many arguments can map have?

The map function has two arguments (1) a function, and (2) an iterable.

How do you pass multiple arguments to a map in Python?

Pass multiple arguments to the map() function in Python # Pass the handler function and the arguments to the functools. partial() method. Pass the result and the iterable to the map() function. The handler function will get called the arguments on each iteration.


2 Answers

First of all, there is no need to use lambda AND partial - they are alternatives:

map(lambda x:f(x,fixed),srclist)

Secondly, you could just bind the second argument with partial, as long as you know the argument's name:

map(functools.partial(f,y=fixed),srclist)

Alternatively, use a list comprehension:

[f(x, fixed) for x in srclist]
like image 192
Marcin Avatar answered Sep 19 '22 18:09

Marcin


What's wrong with:

def add(x, y):
    return x + y

l = [1, 2, 3]

from functools import partial
plus10 = map(partial(add, y=10), l)
print plus10

## [11, 12, 13]
like image 37
georg Avatar answered Sep 18 '22 18:09

georg