2016-10-07 36 views
0

我有像这样一个数组的数组的数组添加量...如何从阵列

a1 = [[9, -1811.4], [8, 959.86], [7, -385], [6, -1731.39], [5, 806.78], [4, 2191.65]] 

我需要从整个阵列的第2个项目(金额)的平均值。

所以添加-1811.4,959.86,-385,-1731.39,806.78由计数分(6)

我已经试过......

a1.inject{ |month, amount| amount }.to_f/a1.size 

这是不对的,我不能看我需要做的

回答

3
a1.map(&:last).inject(:+)/a1.size.to_f 
#=> 5.0833333333332575 

步骤:

# 1. select last elements 
a1.map(&:last) 
#=> [-1811.4, 959.86, -385, -1731.39, 806.78, 2191.65] 
# 2. sum them up 
a1.map(&:last).inject(:+) 
#=> 30.499999999999545 
# 3. divide by the size of a1 
a1.map(&:last).inject(:+)/a1.size.to_f 
#5.0833333333332575 
+0

是否增加时,这种方法把消极到积极? – SupremeA

+0

@SupremeA它没有。它只是总结它。你需要总结绝对值吗? –

+0

是的,我现在看到谢谢! – SupremeA

2

只要通过a1就足够了。

a1.reduce(0) { |tot, (_,b)| tot + b }/a1.size.to_f 
    #=> 5.0833333333332575 

.to_f允许a1只包含整数值。

步骤:

tot = a1.reduce(0) { |tot, (_,b)| tot + b } 
    #=> 30.499999999999545 
n = a1.size.to_f 
    #=> 6.0 
tot/n 
    #=> 5.0833333333332575 
+0

只是另一种选择,我们也可以使用'.fdiv(a1.size)'而不是'/ a1.size.to_f'。 –

+0

@ sagarpandya82,我从来没有听说过[Numeric#fdiv](https://ruby-doc.org/core-2.2.2/Fixnum.html#method-i-fdiv)。谢谢你的提示。 –

+0

也正在考虑添加一个'inject'选项,但它需要输入更多字母才能输入我的原始文字,所以我放弃了它:) –