ruby:对两个或多个数组的对应成员求和 [英] ruby: sum corresponding members of two or more arrays
问题描述
我有两个(或更多)数组,每个数组有 12 个整数(对应于每个月的值).我想要的只是将它们加在一起,这样我就有了一个包含每个月总和值的数组.这是一个包含三个值的示例:[1,2,3] 和 [4,5,6] => [5,7,9]
I've got two (or more) arrays with 12 integers in each (corresponding to values for each month). All I want is to add them together so that I've got a single array with summed values for each month. Here's an example with three values: [1,2,3] and [4,5,6] => [5,7,9]
我能想到的最好的方法是:
The best I could come up with was:
[[1,2,3],[4,5,6]].transpose.map{|arr| arr.inject{|sum, element| sum+element}} #=> [5,7,9]
有没有更好的方法来做到这一点?这似乎是一件很基本的事情.
Is there a better way of doing this? It just seems such a basic thing to want to do.
推荐答案
这是 Anurag 建议的 transpose
版本:
Here's the transpose
version Anurag suggested:
[[1,2,3], [4,5,6]].transpose.map {|x| x.reduce(:+)}
这将适用于任意数量的组件数组.reduce
和 inject
是同义词,但在我看来 reduce
在这里更清楚地传达了代码的意图......
This will work with any number of component arrays. reduce
and inject
are synonyms, but reduce
seems to me to more clearly communicate the code's intent here...
这篇关于ruby:对两个或多个数组的对应成员求和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!