简体   繁体   中英

How can I create a dictionary from two lists while keeping days together?

I have a list of dates and a list of times. How can I create a dictionary with the key as the date and the times as the values using the next date as a key when the hours belong to a different next day (so when a time is less than the previous time)? Both lists are currently strings.

My list of dates:

['2019/07/27',
 '2019/07/29',]

My list of times:

['06:55:40',
 '06:55:41',
 '08:48:33',
 '08:48:33',
 '09:02:54',
 '09:02:54',
 '09:02:54',
 '10:02:19',
 '10:02:20',
 '07:34:52',
 '07:34:52',
 '07:35:03',
 '09:22:19',
 '09:22:19',
 '09:22:19',
 '09:22:23',
 '11:17:24',
 '11:17:27',
 '13:24:57',]

Expected output:

{'2019/07/27': ['06:55:40',
                '06:55:41',
                '08:48:33',
                '08:48:33',
                '09:02:54',
                '09:02:54',
                '09:02:54',
                '10:02:19',
                '10:02:20',],
 '2019/07/29': ['07:34:52',
                '07:34:52',
                '07:35:03',
                '09:22:19',
                '09:22:19',
                '09:22:19',
                '09:22:23',
                '11:17:24',
                '11:17:27',
                '13:24:57',]}
time_groups = []
grp = []
previous_time = None
for time in times:
    if previous_time is None or time > previous_time:
        grp.append(time)
    else:
        time_groups.append(grp)
        grp = []
    previous_time = time

output = {d:t for d,t in zip(dates,time_groups)}

You can do it with this function. It is easier if you convert them to datetime objects for comparison purposes:

from datetime import datetime as dt

def sort_dates(ds, ts):
    limit = dt.strptime("23:59:59", "%H:%M:%S").time()
    res = {}
    i = -1

    for time in ts:
        current = dt.strptime(time, "%H:%M:%S").time()
        if current < limit:
            i+=1
            res[ds[i]] = []
        res[d[i]].append(time)   
        limit = current    

    return res

d = ['2019/07/27', '2019/07/29']
t = ['06:55:40', '06:55:41', '08:48:33', '08:48:33', '09:02:54', '09:02:54', '09:02:54', '10:02:19', '10:02:20', '07:34:52', '07:34:52', '07:35:03', '09:22:19', '09:22:19', '09:22:19', '09:22:23', '11:17:24', '11:17:27', '13:24:57']
res = sort_dates(d, t)

My solution is below. I sliced the list of times.

i = 1
j = 0
length = len(times)
while i < length:
    if times[i-1] > times[i] or i is length-1: # i is the index of the start time on the next day
        dict[dates[j]] = times[:i]
        times = times[i:]
        j += 1
        i = 1
        length = len(times)
    else:
        i += 1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM