Reputation: 107
I have a function which has more than one input variable. For a particular case only one of the input variables is being varied, is it possible to apply this function using a map without having to make a list of the non-varying variables?
For example:
# Example multiple variable input function
def Example_Function(x,y):
return x**2+y**2
# Example List changing variable, x
List_of_x = [x for x in range(0,100)]
# Non-varying y
y = 4
# The naive version of the application (doesn't work)
Naive_Result_of_map_application = list(map(Example_Function, List_of_x, [y]))
# The result we want where we have to make a list of y ([y for i in range(0,100)])
Result_of_map_application = list(map(Example_Function, List_of_x, [y for i in range(0,100)]))
So, is there a way to get Result_of_map_application
without having to do [y for i in range(0,100)]
?
Upvotes: 0
Views: 654
Reputation: 155418
Answering your question as asked:
You can just use itertools.repeat(y)
to make an iterator that produces y
forever (map
will stop when the other iterator is exhausted). If it must stop after a certain number of repetitions, you can pass the count as a second parameter, e.g. itertools.repeat(y, 100)
.
This would make your code:
from itertools import repeat # At top of file
Result_of_map_application = list(map(Example_Function, List_of_x, repeat(y)))
That said, in this circumstance, I'd personally recommend the more readable listcomp provided by Carcigenicate.
Upvotes: 2
Reputation: 45750
I'd personally do away with map
. If you don't want y
to change, I just wouldn't put it in a context that expects changing data. A list comprehension works fine here:
Result_of_map_application = [Example_Function(x, y) for x in List_of_x]
Upvotes: 4
Reputation: 61910
Create a new function that already sets the y
parameter:
# Example multiple variable input function
def example_function(x, y):
return x ** 2 + y ** 2
# Example List changing variable, x
list_of_x = [x for x in range(0, 100)]
# Non-varying y
y = 4
new_example_function = lambda x : example_function(x, y)
# The result we want where we have to make a list of y ([y for i in range(0,100)])
Result_of_map_application = list(map(new_example_function, list_of_x))
As an alternative make them optional, and use partial:
from functools import partial
def example_function(x=1, y=4):
return x ** 2 + y ** 2
list_of_x = [x for x in range(0, 100)]
y = 4
new_example_function = partial(example_function, y=4)
result_of_map_application = list(map(new_example_function, list_of_x))
Upvotes: 2