簡體   English   中英

如何迭代兩個並行的字典值列表?

[英]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()

xy應該遍歷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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM