题
我想知道是否有一种方法可以在 Ruby 中使用 Python 完成以下操作:
sum = reduce(lambda x, y: x + y, map(lambda x, y: x * y, weights, data))
我有两个大小相等、权重和数据相同的数组,但我似乎找不到类似于 Ruby 中的 map 的函数,reduce 我正在工作。
解决方案
@米希尔·德·马雷
您的 Ruby 1.9 示例可以进一步缩短:
weights.zip(data).map(:*).reduce(:+)
另请注意,在 Ruby 1.8 中,如果您需要 ActiveSupport(来自 Rails),您可以使用:
weights.zip(data).map(&:*).reduce(&:+)
其他提示
在 Ruby 1.9 中:
weights.zip(data).map{|a,b| a*b}.reduce(:+)
在 Ruby 1.8 中:
weights.zip(data).inject(0) {|sum,(w,d)| sum + w*d }
Array.zip 函数对数组进行元素组合。它不像 Python 语法那么干净,但您可以使用以下一种方法:
weights = [1, 2, 3]
data = [4, 5, 6]
result = Array.new
a.zip(b) { |x, y| result << x * y } # For just the one operation
sum = 0
a.zip(b) { |x, y| sum += x * y } # For both operations
也适用于 2 个以上数组的映射替代方案:
def dot(*arrays)
arrays.transpose.map {|vals| yield vals}
end
dot(weights,data) {|a,b| a*b}
# OR, if you have a third array
dot(weights,data,offsets) {|a,b,c| (a*b)+c}
这也可以添加到数组中:
class Array
def dot
self.transpose.map{|vals| yield vals}
end
end
[weights,data].dot {|a,b| a*b}
#OR
[weights,data,offsets].dot {|a,b,c| (a*b)+c}
weights = [1,2,3]
data = [10,50,30]
require 'matrix'
Vector[*weights].inner_product Vector[*data] # => 200
不隶属于 StackOverflow