[英]how to map over a function with multiple arguments in python
I'm looking to map over a function with lists for specific arguments. 我正在寻找一个带有特定参数列表的函数。
def add(x, y):
return(x + y)
list1 = [1, 2, 3]
list2 = [3, 4, 5]
After some research I have been able to successfully do it using map
and a lambda
function. 经过一些研究,我已经能够使用
map
和lambda
函数成功完成它。
list(map(lambda x, y: add(x, y), list1, list2))
I was wondering, is it better to do this using an iterator? 我想知道,使用迭代器这样做更好吗? I tried the following but couldn't figure it out:
我尝试了以下但无法弄清楚:
[add(x, y), for x, y in list1, list2]
or 要么
[add(x, y), for x in list1 for y in list2]
Thanks in advance! 提前致谢!
There is no need to use a lambda expression here, you can pass a reference to te function directly: 有没有必要使用lambda表达式在这里,你可以通过直接TE功能的引用:
list(map(
add, list1, list2))
In case you want to use list comprehension , you can use zip
: 如果你想使用列表理解 ,你可以使用
zip
:
[add(x, y) for x, y in
zip(list1, list2
)]
zip
takes n iterables, and generate n -tuples where the i -th tuple contains the i -th element of every iterable. zip
需要n次迭代,并生成n- tuples,其中第i个元组包含每个iterable的第i个元素。
In case you want to add a default value to some parameters, you can use partial
from functools
. 如果您想为某些参数添加默认值,可以使用
functools
partial
。 For instance if you define a: 例如,如果您定义:
def add (x, y, a, b):
return x + y + a + b
from functools import partial
list(map(
partial(add
, a=3, b=4), list1, list2))
Here x
and y
are thus called as unnamed parameters, and a
and b
are by partial
added as named parameters. 因此,
x
和y
被称为未命名参数,并且a
和b
被partial
添加为命名参数。
Or with list comprehension: 或者列表理解:
[add(x, y
, 3, 4) for x, y in zip(list1, list2)]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.