次平均阵列作为Ruby字符串 [英] Average array of times as strings in Ruby

查看:116
本文介绍了次平均阵列作为Ruby字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数组:

 数组= [零时00分31秒,零时00分52秒,0点01分05秒,0点零零分55秒,0: 01:33,〇时00分05秒,0:00:01,
      0时05分10秒,0点02分40秒,0点03分03秒,0点01分33秒,0:00:00]

和我需要的所有平均时代的数组中不等于0:00:000:00:00应该只是扔出去。

什么是做到这一点的最好方法是什么?我目前通过数组循环,清除所有的 0:00:00 值,把字符串转换为整数,做一个平均 - 但好像很多code代表什么,我试图做的。


解决方案

 (SZ = {array.reject | T |牛逼=='〇点零零分00秒'})。
            图{| T | Time.parse T】。
            减少(0){| A,T | A + = t.to_i} .to_f / sz.size

您想将这些东西放到功能操作。拒绝你不需要的东西,那么作用于其余部分。

在这里,减少是一个可行的方式来获得一个数组平均和前面已经回答了。


下面是稍微更简洁是另一种选择,稍微隐晦

 (SZ = {array.reject | T |牛逼=='0:00:00'})。
            图{| T | Time.parse(T).to_i}。
            减少(+)。to_f / sz.size

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" should just be thrown out.

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.

解决方案

(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.


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

这篇关于次平均阵列作为Ruby字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆