[英]How to iterate through two lists which are dictionary values in parallel?
我需要幫助來遍歷此函數中名為'TimeO'
和'TimeC'
的數據字典列。
Data_Dict = {'TimeO': ['9:00:00', '10:00:00'] 'TimeC': ['14:00:00', '16:00:00']}
x
應該是TimeO
值, y
應該是TimeC
值。
我無法弄清楚如何迭代這些值
def timed_duration():
opening = datetime.strptime(x, '%H:%M:%S')
closing = datetime.strptime(y, '%H:%M:%S')
sec =(closing-opening).total_seconds()
hour = sec/3600
return(hour)
timed_duration()
x
和y
應該遍歷400條記錄,但我不知道該怎么做
考慮到您的數據如下所示:
Data_Dict = {'TimeO': ['9:00:00', '10:00:00'], 'TimeC': ['14:00:00', '16:00:00']}
def timed_duration(data_dict):
hours = [] # create an empty list to store all the results
for x, y in zip(data_dict['TimeO'], data_dict['TimeC']):
opening = datetime.strptime(x, '%H:%M:%S')
closing = datetime.strptime(y, '%H:%M:%S')
sec =(closing-opening).total_seconds()
hour = sec/3600
hours.append(hour)
return hours # no parenthesis in return
timed_duration(Data_Dict)
這將創建一個名為hours
的列表,其中包含函數的結果。 zip()
thingy允許您同時迭代兩個對象。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.