Python 3.x 如何将多个参数传递给python映射函数?

Python 3.x 如何将多个参数传递给python映射函数?,python-3.x,lambda,Python 3.x,Lambda,我正在尝试对列表使用map函数。如何将每个距离传递给贴图功能。如果您看到下面的代码,它将计算距离并以列表形式返回输出 import math locations = [[1, 2], [2, 3]] distance = lambda x,y : math.sqrt(x**2 + y**2) output = list(map(distance, locations)) Traceback (most recent call last): File "<stdin>", lin

我正在尝试对列表使用map函数。如何将每个距离传递给贴图功能。如果您看到下面的代码,它将计算距离并以列表形式返回输出

import math
locations = [[1, 2], [2, 3]]
distance = lambda x,y : math.sqrt(x**2 + y**2)
output = list(map(distance, locations))

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: <lambda>() missing 1 required positional argument: 'y'
导入数学
位置=[[1,2],[2,3]]
距离=λx,y:math.sqrt(x**2+y**2)
输出=列表(地图(距离、位置))
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
TypeError:()缺少1个必需的位置参数:“y”
试试:

import math
locations = [[1, 2], [2, 3]]
distance = lambda x,y : math.sqrt(x**2 + y**2)
output = list(map(distance, *locations))
尝试:


您可以使用
math.hypot
函数,而不是编写自己的:

import math
import itertools
locations = (1, 2), (2, 3), (3, 4)
print(*itertools.starmap(math.hypot, locations), sep='\n')

如果您想要两个位置以外的其他位置,请使用
itertools.starmap

您可以使用
math.hypot
函数,而不是编写自己的:

import math
import itertools
locations = (1, 2), (2, 3), (3, 4)
print(*itertools.starmap(math.hypot, locations), sep='\n')

如果您想拥有两个位置以外的其他位置,请使用
itertools.starmap

根据所有答案,我的解决方案如下

import math
import itertools
locations = [[1, 2], [2, 3], [3, 4]]
output = list(itertools.starmap(lambda x,y: math.sqrt(x**2  + y**2), locations))

我将这些计算值发送到另一个函数,因此在我的例子中,我认为将其存储在列表中是唯一的选择

根据所有答案,我的解决方案如下

import math
import itertools
locations = [[1, 2], [2, 3], [3, 4]]
output = list(itertools.starmap(lambda x,y: math.sqrt(x**2  + y**2), locations))

我将这些计算值发送到另一个函数,因此在我的例子中,我认为将其存储在列表中是唯一的选择

首先,注意
list(map(…)
是;阅读清单上的理解。其次,map将始终将整个子列表传递给lambda,因为它是外部列表中的元素。请参见
lambda x:math.sqrt(x[0]**2+x[1]**2)
将是一种方式,但在位置中使用
loc_squared=[math.sqrt(x*x+y*y)表示x,y]
也应该这样做。。。或者使用Patrick Haugh的建议首先,注意
list(map(…)
是;阅读清单上的理解。其次,map将始终将整个子列表传递给lambda,因为它是外部列表中的元素。请参见
lambda x:math.sqrt(x[0]**2+x[1]**2)
将是一种方式,但在位置中使用
loc_squared=[math.sqrt(x*x+y*y)表示x,y]
也应该这样做。。。或者使用Patrick Haugh的建议,如果您提供有关该*locations运营商的更多信息,对其他人来说将是一件好事。如果您提供有关该*locations运营商的更多信息,对其他人来说将是一件好事。是否有将其存储为列表的最佳做法?看起来使用
list(*itertools.starmap(math.hypot,locations))
不是一个好方法practice@ajayramesh这取决于处理数据后要对数据做什么。如果你想看一眼,那你是对的;将结果存储在列表(或元组)中并不是最佳选择。您应该简单地对其进行迭代。另一方面,如果您计划多次查看处理后的数据,则最好将其存储在列表或元组(或其他存储结构)中。如果看不到更多的代码,就很难再提供帮助了。有什么最佳做法可以将其存储为列表吗?看起来使用
list(*itertools.starmap(math.hypot,locations))
不是一个好方法practice@ajayramesh这取决于处理数据后要对数据做什么。如果你想看一眼,那你是对的;将结果存储在列表(或元组)中并不是最佳选择。您应该简单地对其进行迭代。另一方面,如果您计划多次查看处理后的数据,则最好将其存储在列表或元组(或其他存储结构)中。如果看不到更多的代码,就很难再提供帮助了。