如何对两个并行的字典值列表进行迭代?

时间:2019-04-08 07:19:51

标签: python loops dictionary

我需要帮助来遍历此函数中名为'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条记录,但我不知道该怎么做

1 个答案:

答案 0 :(得分:0)

考虑数据如下:

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()可以让您同时遍历两个对象。

相关问题