如何总结上唯一键嵌套数组中的多个元素 [英] How to sum multiple elements of nested arrays on unique keys
问题描述
我有以下定义的表。对于每行中的每个元素的索引对应于相同的字段
I have the following defined table. The index for each element in each row corresponds to the same field.
[[123.0, 23,"id1",34, "abc"],
[234.1,43, "id2", 24,"jsk"],
[423.5,53, "id1",1,"xyz"],
[1.4, 5, "id2",0,"klm"]]
在上面的例子中,我需要组和总结,总结各对中的第3列的唯一标识符索引中的可累加元件的输出。其结果应该是这样的:
In the above example I need to group and sum an output that sums each of the summable elements on the index for the unique identifier in the 3rd column. The result should look like this:
[[546.5,76, "id1",35],
[235.5,48, "id2",24]]
什么是做到这一点的最好方法是什么?
What's the best way to do this?
推荐答案
这在本质上是相同的解决您的 previous问题。
This is essentially the same as the solution to your previous question.
data = [ [ 123.0, 23, "id1", 34, "abc" ],
[ 234.1, 43, "id2", 24, "jsk" ],
[ 423.5, 53, "id1", 1, "xyz" ],
[ 1.4, 5, "id2", 0, "klm" ] ]
sums = Hash.new {|h,k| h[k] = [0, 0, 0] }
data.each_with_object(sums) do |(val0, val1, id, val2, _), sums|
sums[id][0] += val0
sums[id][1] += val1
sums[id][2] += val2
end
# => { "id1" => [ 546.5, 76, 35 ],
# "id2" => [ 235.5, 48, 24 ] }
的主要区别是,而不是给哈希 0
的默认值,我们给它以 [0,0,0]
。 (我们不能只是做 Hash.new([0,0,0])
,因为那么每值将是一个数组实例的引用,而不是每个值有自己的数组。)然后,块里面,我们每个值( val0
等)添加到款项[ID]的相应元素
。
The main difference is that instead of giving the Hash a default value of 0
, we're giving it a default proc that initializes missing keys with [0, 0, 0]
. (We can't just do Hash.new([0, 0, 0])
because then every value would be a reference to a single Array instance, rather than each value having its own Array.) Then, inside the block, we add each value (val0
et al) to the corresponding elements of sums[id]
.
如果你想要一个数组的数组,而不是用 ID
索引2哈希,然后在最后,你将不得不增加一些这样的:
If you wanted an Array of Arrays instead of a Hash with the id
at index 2, then at the end, you would have to add something like this:
.map {|id, vals| vals.insert(2, id) }
然而,在ID作为密钥的散列更有意义作为数据结构
However, a Hash with the ids as keys makes more sense as a data structure.
这篇关于如何总结上唯一键嵌套数组中的多个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!