使用 map 解包 iterable
Unpacking iterable using map
假设我有两个相同长度的数字迭代
weights = range(0, 10)
values = range(0, 100, 10)
我需要计算加权总和。我知道可以通过列表理解来完成
weighted_sum = sum(weight * value for weight, value in zip(weights, values))
我想知道是否可以使用map
and operator.mul
like
来完成
import operator
weighted_sum = sum(map(operator.mul, zip(weights, values)))
但这会出错
Traceback (most recent call last):
File "<input>", line 3, in <module>
TypeError: op_mul expected 2 arguments, got 1
所以我的问题是:有没有什么方法可以使用 map
传递未打包的元组以发挥作用?
试试这个:
>>> import operator
>>>
>>> weights = range(0, 10)
>>> values = range(0, 100, 10)
>>> sum(map(lambda i:operator.mul(*i), zip(weights, values)))
2850
或者
>>> sum(map(operator.mul, weights, values))
2850
map
不需要 zip
,只需使用
weighted_sum = sum(map(operator.mul, weights, values))
If additional iterable arguments are passed, function must take that many arguments and is applied to the items from all iterables in parallel.
map
的文档中还提到,对于已经 zip
的输入,您可以使用 itertools.starmap
而不是 map
。
与 一样,在处理数字时使用 numpy
总是一个好主意,实际上类似于
import numpy as np
np.asarray(weights) * values
已经可以解决这个问题了(尽管与 map
相比,这个 要求 两个数组的长度相同,而 map
会映射最短长度)。
您也可以尝试 numpy
,
In [45]: import numpy as np
In [46]: sum(map(np.multiply,weights,values))
Out[46]: 2850
根据 Tobias Kienzler 的建议,
In [52]: np.sum(np.array(weights) * values)
Out[52]: 2850
假设我有两个相同长度的数字迭代
weights = range(0, 10)
values = range(0, 100, 10)
我需要计算加权总和。我知道可以通过列表理解来完成
weighted_sum = sum(weight * value for weight, value in zip(weights, values))
我想知道是否可以使用map
and operator.mul
like
import operator
weighted_sum = sum(map(operator.mul, zip(weights, values)))
但这会出错
Traceback (most recent call last):
File "<input>", line 3, in <module>
TypeError: op_mul expected 2 arguments, got 1
所以我的问题是:有没有什么方法可以使用 map
传递未打包的元组以发挥作用?
试试这个:
>>> import operator
>>>
>>> weights = range(0, 10)
>>> values = range(0, 100, 10)
>>> sum(map(lambda i:operator.mul(*i), zip(weights, values)))
2850
或者
>>> sum(map(operator.mul, weights, values))
2850
map
不需要 zip
,只需使用
weighted_sum = sum(map(operator.mul, weights, values))
If additional iterable arguments are passed, function must take that many arguments and is applied to the items from all iterables in parallel.
map
的文档中还提到,对于已经 zip
的输入,您可以使用 itertools.starmap
而不是 map
。
与 numpy
总是一个好主意,实际上类似于
import numpy as np
np.asarray(weights) * values
已经可以解决这个问题了(尽管与 map
相比,这个 要求 两个数组的长度相同,而 map
会映射最短长度)。
您也可以尝试 numpy
,
In [45]: import numpy as np
In [46]: sum(map(np.multiply,weights,values))
Out[46]: 2850
根据 Tobias Kienzler 的建议,
In [52]: np.sum(np.array(weights) * values)
Out[52]: 2850