解决方案
Ruby有一个map
方法(又称collect
方法),可以应用于任何Enumerable
对象。如果numbers
是数字数组,则Ruby中这样写:
numbers.map{|x| x + 5}
与Python中下面代码是一样的:
map(lambda x: x + 5, numbers)
另外,Array.zip函数对数组进行逐元素组合。我们可以使用以下一种方法:
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
在Ruby 1.9中:
weights.zip(data).map{|a,b| a*b}.reduce(:+) 或者 weights.zip(data).map(:*).reduce(:+)
在Ruby 1.8中:
weights.zip(data).map(&:*).reduce(&:+) 或者 weights.zip(data).inject(0) {|sum,(w,d)| sum + w*d }
在Python中,我们可以这样写
sum = reduce(lambda x, y: x + y, map(lambda x, y: x * y, weights, data))
在Ruby中,有没有类似python map()这样的函数
日期:2020-03-24 14:32:26 来源:oir作者:oir