2

我有 3 个列表,一个是小时,一个是分钟,一个是秒。我所做的是创建一个函数,它将 3 个列表作为输入并计算总时间。

我的问题是该功能是如此多余,我对您的问题很简单:什么是更好的方法来做到这一点。

这是我的功能:

def final_time(hours,minutes,seconds):
    draft_hours = sum(hours)
    draft_minutes = sum(minutes)
    draft_seconds = sum(seconds)
    adding_seconds = str(draft_seconds/60.0)
    second_converting = adding_seconds.split(".")
    seconds_to_minutes = int(second_converting[0])
    seconds_to_seconds = draft_seconds - (seconds_to_minutes * 60)
    total_seconds = str(seconds_to_seconds)
    more_minutes = draft_minutes + seconds_to_minutes
    adding_minutes = str(more_minutes/60.0)
    minute_converting = adding_minutes.split(".")
    minutes_to_hours = int(minute_converting[0])
    minutes_to_minutes = more_minutes - (minutes_to_hours * 60)
    total_minutes = str(minutes_to_minutes)
    total_hours = str(draft_hours + minutes_to_hours)
    return total_hours + " hours, " + total_minutes + " minutes, and " + total_seconds + " seconds."

这是一个例子:

my_hours = [5, 17, 4, 8]
my_minutes = [40, 51, 5, 24]
my_seconds = [55, 31, 20, 33]
print final_time(my_hours,my_minutes,my_seconds)

以上回报:

36 hours, 2 minutes, and 19 seconds.

所以它确实有效,但正如你所看到的,该函数既不是pythonic也不是高效函数......更好的方法是什么?

4

4 回答 4

6
s = sum(hours)*3600+sum(minutes)*60+sum(seconds)
return '%d hours %d minutes %d seconds'%( s/3600, (s%3600)/60, s%60)
于 2013-04-29T17:07:26.110 回答
4

我可能会先将其全部转换为秒:

seconds = sum(3600*h + 60*m + s for (h,m,s) in zip(hours,minutes,seconds)

现在将其分解:

n_hours,minutes = divmod(seconds,3600)
n_minutes,n_seconds = divmod(minutes,60)
于 2013-04-29T17:07:30.650 回答
3
def HMSToSeconds(H,M,S):
   return H*3600 + M * 60 + S

def SecondsToHMS(seconds):
   hours,seconds = divmod(seconds,3600)
   mins,seconds = divmod(seconds,60)
   return hours,mins,seconds

def final_time(hours,minutes,seconds):
    draft_hours = sum(hours)
    draft_minutes = sum(minutes)
    draft_seconds = sum(seconds)
    total_seconds = HMSToSeconds(draft_hours,draft_minutes,draft_seconds)
    return SecondsToHMS(total_seconds)
于 2013-04-29T17:06:49.410 回答
0

我会使用来自 Datetime http://docs.python.org/2/library/datetime.html#time-objects的时间对象

那将是这样的:

def final_time(hours,minutes,seconds):
    times=[datetime.time(hours[i],minutes[i],seconds[i]) for i in range(0,length(hours))]
    return sum(times)
于 2013-04-29T17:09:20.633 回答