简体   繁体   English

如何在Ruby中获取数组第二列的最大值和总和

[英]how to get max and sum of 2nd column of array in ruby

for an array like 对于像这样的数组

s = [[1,2],[4,6],[2,7]] s = [[1,2],[4,6],[2,7]]

How i can select max and sum of 2nd column in each row in one statement 我如何在一条语句中选择每一行的第二列的最大值和和

max= 7 最大= 7
sum= 15 总和= 15

I know, that 我知道

sum = 0
max = 0
s.each{ |a,b| sum+=b;if max<b then max = b end }

would work. 会工作。

second_elements = s.map { |el| el[1] }
sum = second_elements.inject{|sum,x| sum + x }
max = second_elements.max

To be more clear: inject{|sum,x| sum + x } 更清楚的是: inject{|sum,x| sum + x } inject{|sum,x| sum + x } returns nil if array is empty, so if you want to get 0 for empty array then use inject(0, :+) inject{|sum,x| sum + x }如果数组为空,则返回nil,所以如果要为空数组获取0,则使用inject(0, :+)

The transpose method is nice for accessing "columns": transpose方法非常适合访问“列”:

s = [[1,2],[4,6],[2,7]]
col = s.transpose[1]
p col.max #=> 7
p col.inject(:+) #=> 15
s.max {|a| a[1]}[1]          # Max of elements at index 1
s.max {|a| a.last }.last     # Max of last elements
# => 7

To find the sum, if you use Ruby 2.4 or greater / if you are on Rails 如果您使用Ruby 2.4或更高版本,/如果您在Rails上,则要求和

s.sum {|a| a[1]}             # Sum of elements at index 1
s.sum(&:last)                # Sum of last elements
# => 15

else 其他

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

s.map{|e| e[1]}.max s.map{|e| e[1]}.max gives you max s.map{|e| e[1]}.max给您最大

s.map{|e| e[1]}.reduce(:+) s.map{|e| e[1]}.reduce(:+) gives you sum. s.map{|e| e[1]}.reduce(:+)为您求和。

s = [[1,2],[4,6],[2,7]]
second_max = s.max_by(&:last).last 
# => 7
sum = s.reduce(0){|sum,a| sum + a.last}
# => 15

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM