合并或&QUOT总结2阵列;键"在红宝石 [英] Merge or sum 2 arrays on "keys" in ruby
问题描述
这是数组版本:总和2哈希有属性相同的密钥
我有2个阵列,例如:
A = [[1,10],[2,20],[3,30]
B = [1,50],[3,70]
我怎么能和每一对的第一个值(如果存在的话),以获得:
C = [1,60],[2,20],[3100]
您可以做到这一点正是如此:
(A + B).group_by(安培;:第一).MAP {| K,V | [K,v.map(安培;:最后一个).inject(+)]}
首先你把阵列连同 +
既然你不关心 A
和 b
,你只关心自己的元素。然后,<一个href=\"http://www.ruby-doc.org/core-1.9.3/Enumerable.html#method-i-group_by\"><$c$c>group_by$c$c>分区由第一元件,以便内部阵列可容易地与被加工的组合阵列。然后你只需要拉出阵列内的第二个(或最后一个)元素与<一个href=\"http://www.ruby-doc.org/core-1.9.3/Enumerable.html#method-i-map\"><$c$c>v.map(&:last)$c$c>和<一笔他们href=\"http://www.ruby-doc.org/core-1.9.3/Enumerable.html#method-i-inject\"><$c$c>inject(:+)$c$c>.
例如:
&GT;&GT;一个= [[1,10],[2,20],[3,30]
&GT;&GT; B = [1,50],[3,70]
&GT;&GT; (A + B).group_by(安培;:第一).MAP {| K,V | [K,v.map(安培;:最后一个).inject(+)]}
= GT; [[1,60],[2,20],[3,100]]
This is the array version of: Sum 2 hashes attributes with the same key
I have 2 arrays, for example:
a = [[1,10],[2,20],[3,30]]
b = [[1,50],[3,70]]
How can i sum each on the first value (if it exists) to get:
c = [[1,60],[2,20],[3,100]]
You could do it thusly:
(a + b).group_by(&:first).map { |k, v| [k, v.map(&:last).inject(:+)] }
First you put the arrays together with +
since you don't care about a
and b
, you just care about their elements. Then the group_by
partitions the combined array by the first element so that the inner arrays can easily be worked with. Then you just have to pull out the second (or last) elements of the inner arrays with v.map(&:last)
and sum them with inject(:+)
.
For example:
>> a = [[1,10],[2,20],[3,30]]
>> b = [[1,50],[3,70]]
>> (a + b).group_by(&:first).map { |k,v| [k, v.map(&:last).inject(:+)] }
=> [[1, 60], [2, 20], [3, 100]]
这篇关于合并或&QUOT总结2阵列;键&QUOT;在红宝石的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!