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屋!