2013-04-29 47 views
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或高效函數... 什麼是更好的方法?

+2

即開始的問題,「*所以它的工作*」爲更好地要求在http://codereview.stackexchange.com – 2013-04-29 17:18:36

回答

6
s = sum(hours)*3600+sum(minutes)*60+sum(seconds) 
return '%d hours %d minutes %d seconds'%(s/3600, (s%3600)/60, s%60) 
+0

我喜歡你的轉換,以秒比我更多。我認爲'小時','分鐘'和'秒'中有相同數量的元素,但我想我沒有看到任何理由爲什麼總是這樣。 (1) – mgilson 2013-04-29 17:09:23

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) 
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)