Python 用两个参数定义lambda函数

Python 用两个参数定义lambda函数,python,Python,我有一些代码如下所示 import math square_root = lambda x: math.sqrt(x) list = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16] map(square_root,list) 输出: [1.0, 1.4142135623730951, 1.7320508075688772, 2.0, 2.23606797749979, 2.449489742783178, 2.6457513110645907,

我有一些代码如下所示

import math
square_root = lambda x: math.sqrt(x)
list = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]
map(square_root,list)
输出:

[1.0,
 1.4142135623730951,
 1.7320508075688772,
 2.0,
 2.23606797749979,
 2.449489742783178,
 2.6457513110645907,
 2.8284271247461903,
 3.0,
 3.1622776601683795,
 3.3166247903554,
 3.4641016151377544,
 3.605551275463989,
 3.7416573867739413,
 3.872983346207417,
 4.0]
现在我想用幂来代替平方根

import math
power = lambda x: math.power(x,n)
list = [1,2,3,4,5]
map(power,list,2)
我得到了以下错误?如何在map中使用两个参数? TypeError回溯(最近一次调用上次) /home/AD/karthik.sharma/ws_karthik/trunk/in() ---->1个地图(电源,列表,2个)


TypeError:map()的参数3必须支持迭代

一种方法如下:

power = lambda x, n: math.pow(x,n)
list = [1,2,3,4,5]
map(power,list,[2]*len(list))
表达式
[2]*len(list)
创建另一个与现有列表长度相同的列表,其中每个元素包含值2。
map
函数从每个输入列表中获取一个元素,并将其应用于
power
函数

另一种方式是:

power = lambda x, n: math.pow(x,n)
list = [1,2,3,4,5]
map(lambda x: power(x, 2),list)
它使用部分应用程序创建第二个lambda函数,该函数只接受一个参数,并将其提升到二次方

请注意,应该避免使用name
list
作为变量,因为它是内置Python
list
类型的名称。

如下所示:

import math
power = lambda n: lambda x: math.pow(x,n)
list = [1,2,3,4,5]
map(power(2),list)
power = lambda x, n: math.pow(x,n)
list = [1,2,3,4,5]
map(lambda x: power(x, 2), list)

列表理解是另一种选择:

list = [1,2,3,4,5]
[math.pow(x,2) for x in list]

您还可以使用
map(power,list,itertools.repeat(2,len(list))
来避免创建第二个列表。如果您想变得非常花哨,可以使用
itertools.cycle([2])
而不是
[2]*len(list)