python - 是否可以在 lambda 函数中包含多个方程

标签 python lambda

我试图在 lambda 函数中包含具有不同长度的变量的多个操作,即:

$ serial_result = map(lambda x,y:(x**2,y**3), range(20), range(10))

但这不起作用。有人可以告诉我如何解决这个问题吗? 我的理解是:

$ serial_result = map(lambda x,y:(x**2,y**3), range(0,20,2), range(10))

之所以有效,是因为“x”和“y”的数组具有相同的长度。

最佳答案

如果您想要范围项目的产品,您可以使用itertools.product:

>>> from itertools import product
>>> serial_result = map(lambda x:(x[0]**2,x[1]**3), product(range(20), range(10)))

如果你想像第二种情况一样将这些对传递给 lambda,你可以使用 itertools.zip_longest(在 python 2 中使用 izip_longest)并传递一个 fillvalue 来填充缺失的值项目,

>>> from itertools import zip_longest
>>> serial_result = map(lambda x:(x[0]**2,x[1]**3), zip_longest(range(20), range(10),fillvalue=1))

请注意,如果您使用的是 python 2,您可以将多个参数作为元组传递给 lambda :

>>> serial_result = map(lambda (x,y):(x**2,y**3), product(range(20), range(10)))

在以下示例中查看 izip_longestproduct 的区别:

>>> list(product(range(5),range(3)))
[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2), (3, 0), (3, 1), (3, 2), (4, 0), (4, 1), (4, 2)]
>>> list(zip_longest(range(5),range(3)))
[(0, 0), (1, 1), (2, 2), (3, None), (4, None)]
>>> list(zip_longest(range(5),range(3),fillvalue=1))
[(0, 0), (1, 1), (2, 2), (3, 1), (4, 1)]

关于python - 是否可以在 lambda 函数中包含多个方程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32236295/

相关文章:

python - Pandas 与 PEP8 : Selecting True values in a Series with mixed types

python - 如何使用 wreq 在 haskell 中发出 json 请求?

python - 在Python中运行sql server查询时出现错误

python - 不区分大小写的正则表达式返回原始模式

LINQ:点表示法与查询表达式

python - AWS lambda 函数错误

python - Pandas 散点图日期时间

python - 对 .apply 和 lambda 的用法感到困惑

Ruby lambda 文字语法

c++ - 在 C++ 中使用函数嵌套无捕获 lambda?