如何在二维数组中对特定值求和

时间:2021-06-13 21:21:53

Let's say, I have this array

让我们说,我有这个数组

arr = [["Ready", 6], ["Draft", 3], ["To Repair", 4], ["Closed", 2]]

My goal is to show these data in percents instead of absolute values. Here is what I want to get:

我的目标是以百分比而不是绝对值显示这些数据。这是我想要的:

[["Ready", 0.5], ["Draft", 0.2], ["To Repair", 0.3], ["Closed", 0.2]]

That means I have to get the sum first. What I tried to do is:

这意味着我必须先得到这笔钱。我试图做的是:

arr.inject {|sum, a| sum + a[1]}

but this returns TypeError Exception: no implicit conversion of Fixnum into Array. Any suggestions?

但是这会返回TypeError异常:没有将Fixnum隐式转换为Array。有什么建议?

3 个解决方案

#1


a[0] is a string; you want a[1]. And starting from sum = 0 and not from sum = ["Ready, 6] is good - so you need the parameter to inject:

a [0]是一个字符串;你想要一个[1]。从sum = 0而不是sum = [“Ready,6]开始是好的 - 所以你需要注入的参数:

sum = arr.inject(0) { |sum, a| sum + a[1] }.to_f
arr.each { |el| el[1] /= sum }
# => [["Ready", 0.4], ["Draft", 0.2], ["To Repair", 0.26666666666666666], ["Closed", 0.13333333333333333]] 

#2


If you want to add the numbers, you should access the element at index 1, and provide an initial value for sum.

如果要添加数字,则应访问索引1处的元素,并为sum提供初始值。

arr.inject(0) {|sum, a| sum + a[1]}
# => 15

#3


A lazy (but not the most effieicnt) way is:

懒惰(但不是最有效)的方式是:

arr.map(&:last).inject(:+)

#1


a[0] is a string; you want a[1]. And starting from sum = 0 and not from sum = ["Ready, 6] is good - so you need the parameter to inject:

a [0]是一个字符串;你想要一个[1]。从sum = 0而不是sum = [“Ready,6]开始是好的 - 所以你需要注入的参数:

sum = arr.inject(0) { |sum, a| sum + a[1] }.to_f
arr.each { |el| el[1] /= sum }
# => [["Ready", 0.4], ["Draft", 0.2], ["To Repair", 0.26666666666666666], ["Closed", 0.13333333333333333]] 

#2


If you want to add the numbers, you should access the element at index 1, and provide an initial value for sum.

如果要添加数字,则应访问索引1处的元素,并为sum提供初始值。

arr.inject(0) {|sum, a| sum + a[1]}
# => 15

#3


A lazy (but not the most effieicnt) way is:

懒惰(但不是最有效)的方式是:

arr.map(&:last).inject(:+)