如何遍历两个并行的字典值列表?

2024-09-27 00:18:28 发布

您现在位置:Python中文网/ 问答频道 /正文

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


Tags: 数据函数datadatetime字典secdictduration
1条回答
网友
1楼 · 发布于 2024-09-27 00:18:28

考虑到您的数据如下所示:

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()允许您同时遍历这两个对象

相关问题 更多 >

    热门问题