简体   繁体   English

我如何找到平均时间?

[英]How do I find the average time?

I am currently working on this project and have some issues finding the average time based on their corresponding types.我目前正在研究这个项目,但在根据相应类型查找平均时间时遇到了一些问题。 For now, I have my output as shown below after reading my CSV file.现在,在阅读我的 CSV 文件后,我的输出如下所示。

#Following this format (x typeList : timeTakenList)

0 Lift : 5 days, 5:39:00
1 Lift : 5 days, 5:31:00
2 lighting : 3 days, 9:47:00
3 ACMV : 5 days, 5:21:00
4 lighting : 3 days, 9:32:00
.
.
.

How do I calculate the average time taken for each type such that I have the following output?如何计算每种类型所花费的平均时间,以便获得以下输出?

0 Lift : (5 days, 5:31:00 + 5 days, 5:39:00) / 2
1 lighting : (3 days, 9:47:00 + 3 days, 9:32:00) / 2
2 ACMV : 5 days, 5:21:00
.
.
.

The timeTakenList is calculated from subtracting another column, Acknowledged Date from the column CompletedDate. timeTakenList 是通过从 CompletedDate 列中减去另一列 Acknowledged Date 计算得出的。

timeTakenList = completedDate - acknowledgedDate

There is a ton of other types in the typeList and I'm trying to avoid doing an if statement like if typeList[x] == "Lift", then add the time together, etc. typeList 中有大量其他类型,我试图避免执行 if typeList[x] == "Lift" 之类的 if 语句,然后将时间加在一起等。

Example of .csv file: .csv 文件示例:

在此处输入图片说明

I'm not too sure how else to make my question clearer, but any help is much appreciated.我不太确定如何使我的问题更清楚,但非常感谢任何帮助。

check the below implementation.检查下面的实现。

import re

typeList = ["Lighting", "Lighting", "Air-Con", "Air-Con", "Toilet"]

timeTakenList = ["10hours", "5hours", "2days, 5hrs", "5hours", "4hours"]

def convertTime(total_time):
    li = list(map(int,re.sub(r"days|hrs|hours","",total_time).split(",")))
    if len(li) == 2:
        return li[0] * 24 + li[1]
        return li[0]

def convertDays(total_time):
    days = int(total_time / 24)
    hours = total_time % 24
    if (hours).is_integer():
        hours = int(hours)
    if days == 0:
        return str(hours) + "hours"
    return str(days) + "days, " + str(hours) + "hrs"

def avg(numbers):
    av = float(sum(numbers)) / max(len(numbers), 1)
return av 

avgTime = {}

for i, types in enumerate(typeList):
    if avgTime.has_key(types):
        avgTime[types].append(convertTime(timeTakenList[i]))
    else:
        avgTime[types] = [convertTime(timeTakenList[i])]

for types in avgTime.keys():
    print types + " : " + convertDays(avg(avgTime[types]))

Algo算法

  • Convert strip "hours", "hrs", "days" from the timeTakenList list.从 timeTakenList 列表中转换带“小时”、“小时”、“天”。
  • convert the elements consisting of days and hours into hours for easier avg calculation将由天和小时组成的元素转换为小时,以便于计算平均值
  • create hash having typeList elements as keys and converted timeTakenList elements as list of values创建将 typeList 元素作为键并将转换后的 timeTakenList 元素作为值列表的哈希
  • print the values for each key converted back to days and hours.打印转换回天和小时的每个键的值。

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

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