[英]Unpacking iterable using map
Assuming I have two iterables of numbers of the same length 假设我有两个相同长度的迭代数
weights = range(0, 10)
values = range(0, 100, 10)
I need to count weighted sum. 我需要计算加权和。 I know that it can be done with list comprehension 我知道可以用列表理解来完成它
weighted_sum = sum(weight * value for weight, value in zip(weights, values))
I wonder if it can be done using map
and operator.mul
like 我想知道是否可以使用map
和operator.mul
来完成
import operator
weighted_sum = sum(map(operator.mul, zip(weights, values)))
but this gives an error 但这会给出错误
Traceback (most recent call last):
File "<input>", line 3, in <module>
TypeError: op_mul expected 2 arguments, got 1
so my question: is there any way of passing unpacked tuples to function using map
? 所以我的问题:有没有办法将解压缩的元组传递给使用map
函数?
Try this: 尝试这个:
>>> import operator
>>>
>>> weights = range(0, 10)
>>> values = range(0, 100, 10)
>>> sum(map(lambda i:operator.mul(*i), zip(weights, values)))
2850
Or 要么
>>> sum(map(operator.mul, weights, values))
2850
map
doesn't need the zip
, just use map
不需要zip
,只需使用
weighted_sum = sum(map(operator.mul, weights, values))
From map
's Documentation 来自map
的文档
If additional iterable arguments are passed, function must take that many arguments and is applied to the items from all iterables in parallel. 如果传递了其他可迭代参数,则函数必须采用那么多参数,并且并行地应用于所有迭代的项。
Also mentioned in map
's documentation is that instead you can use itertools.starmap
instead of map
for already zip
ped input. 在map
的文档中还提到,相反,您可以使用itertools.starmap
而不是map
来获取已经zip
输入。
As Rahul hinted at , using numpy
is always a good idea when dealing with numerics, actually something like 正如拉胡尔暗示的那样 ,使用numpy
在处理数字时总是一个好主意,实际上就像是
import numpy as np
np.asarray(weights) * values
already should do the trick (though in contrast to map
this requires the two arrays to be of same length, while map
would map the shortest length). 已经应该做的伎俩(虽然与map
相比,这需要两个数组具有相同的长度,而map
将映射最短的长度)。
You can also attempt with numpy
, 你也可以尝试numpy
,
In [45]: import numpy as np
In [46]: sum(map(np.multiply,weights,values))
Out[46]: 2850
As per Tobias Kienzler's Suggestion, 根据Tobias Kienzler的建议,
In [52]: np.sum(np.array(weights) * values)
Out[52]: 2850
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.