[英]Average array of times as strings in Ruby
I have an array: 我有一个数组:
array = ["0:00:31", "0:00:52", "0:01:05", "0:00:55", "0:01:33", "0:00:05", "0:00:01",
"0:05:10", "0:02:40", "0:03:03", "0:01:33", "0:00:00"]
and I need to average all of the times in the array that are not equal to "0:00:00"
. 并且我需要平均数组中所有不等于
"0:00:00"
。 "0:00:00"
should just be thrown out. 应该只抛出
"0:00:00"
。
What's the best way to do this? 最好的方法是什么? I'm currently looping through the array, removing all of the
0:00:00
values, turning the strings into integers and doing an average - But it seems like a lot of code for what I'm trying to do. 我目前正在遍历数组,删除所有
0:00:00
值,将字符串转换为整数并进行平均-但对于我想做的事情,似乎有很多代码。
(sz = array.reject {|t| t == '0:00:00' }).
map {|t| Time.parse t }.
reduce(0) {|a, t| a += t.to_i }.to_f / sz.size
You want to group these things into functional operations. 您要将这些东西归为功能性操作。 Reject the stuff you don't need, then act on the rest.
拒绝不需要的东西,然后对其余的东西采取行动。
Here, reduce
is a viable way to get an array average, and has been answered before. 在这里,
reduce
是获得数组平均值的可行方法, 并且之前已经有人回答过。
here is an alternative that is slightly more concise, slightly more cryptic 这是一个更简洁,更神秘的选择
(sz = array.reject {|t| t == '0:00:00' }).
map {|t| Time.parse(t).to_i }.
reduce(:+).to_f / sz.size
Tweaking NewAlexandria's answer to return average in seconds: 调整NewAlexandria的答案以秒为单位返回平均值:
(sz = array.reject {|t| t == '0:00:00' }).
map {|t| t.split(":").inject(0){|product,n| product * 60 + n.to_i} }.
reduce(0) {|a, t| a += t.to_i }.to_f / sz.size
I am not getting NewAlexandria's answer to work for some reason, here is how I would do it: 由于某种原因,我没有得到NewAlexandria的答复,这是我的处理方法:
def average_of_times(array)
zero_seconds = ->x{ x=='0:00:00' }
covert_to_seconds = ->x do
hours, minutes, seconds = x.split(':').map(&:to_i)
hours * 3600 + minutes * 60 + seconds
end
seconds = array.reject!(&zero_seconds)
.map(&covert_to_seconds)
.reduce(:+) / array.size
Time.at(seconds).utc.strftime("%H:%M:%S")
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.