我有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也不是一个有效的函数...... 什么是更好的方法?
答案 0 :(得分:6)
s = sum(hours)*3600+sum(minutes)*60+sum(seconds)
return '%d hours %d minutes %d seconds'%( s/3600, (s%3600)/60, s%60)
答案 1 :(得分: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)
答案 2 :(得分: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)
答案 3 :(得分: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)