简体   繁体   English

如何在数组数组中添加值?

[英]How do I add values in an array of arrays?

I have an array of arrays with four integer elements like this: 我有一个数组,其中包含四个整数元素,如下所示:

arrays = [[a1,b1,c1,d1],[a2,b2,c2,d2],[a3,b3,c3,d3]] 

I want to add these three arrays. 我要添加这三个数组。 The result should be in one array like: 结果应该在一个数组中,例如:

result = [a1+a2+a3,b1+b2+b3,c1+c2+c3,d1+d2+d3]

I tried but not able to do this. 我尝试了但无法做到这一点。

>> arrays = [[1,2,3,4],[2,3,4,5],[3,4,5,6]]
=> [[1, 2, 3, 4], [2, 3, 4, 5], [3, 4, 5, 6]]
>> arrays.transpose.map { |xs| xs.inject :+ }
=> [6, 9, 12, 15]

由于您使用的是Rails,因此可以使用:

arrays.transpose.map &:sum

Here's a quick example: 这是一个简单的示例:

a = [1, 2, 3] 
b = [4, 5, 6] 
c = [7, 8, 9]

[a, b, c].transpose.map { |x| x.reduce :+ } 

=> [12, 15, 18]

For further clarification see " Some Array magic using transpose, map and reduce ". 有关更多说明,请参见“ 一些使用转置,映射和归约的数组魔术 ”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 当存在空条目时,如何在数组中添加值? - How do I add values in an array when there is a null entry? 我有一个内部包含 arrays 的数组:我如何消除这些划分,并且所有内容都只保留在一个数组中? - I have an array with arrays inside: how do I eliminate these divisions and everything stay together in an array only? 如何基于不在另一个数组中的值创建一个数组? - How do I create an array based of values that are not in another array? 如何在另一个记录数组的开头添加一个记录数组? - How do I add an array of records at the beginning of another array of records? 在Rails 4中使用postgres数组,如何返回数组中所有唯一项的数组? - Using postgres arrays in Rails 4, how do I return an array of all the unique items in the array? 如何将两个数组加在一起并收集其中一个或两个都可以为null的id - How do I add two arrays together and collect ids where one or both can be null 如何通过Rails的cycle()值数组循环? - How do I pass Rails' cycle() an array of values to cycle through? 如何通过哈希值在JSON哈希数组中进行搜索? - How do I search within an JSON array of hashes by hash values? 如何从哈希中提取数组值? - How do I extract array values from hashes? 如何将某些值存储在新数组中的 JSON 散列中? - How do I store certain values in a JSON hash in a new array?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM