pythonlistfillforward

Python list forward fill elements according to thresholds


I have a list

a = ["Today, 30 Dec",
     "01:10",
     "02:30",
     "Tomorrow, 31 Dec", 
     "00:00",
     "04:30",
     "05:30",
     "01 Jan 2023",
     "01:00",
     "10:00"]

and would like to kind of forward fill this list so that the result looks like this

b = ["Today, 30 Dec 01:10",
     "Today, 30 Dec 02:30",
     "Tomorrow, 31 Dec 00:00",
     "Tomorrow, 31 Dec 04:30",
     "Tomorrow, 31 Dec 05:30",
     "01 Jan 2023 01:00",
     "01 Jan 2023 10:00"]

Solution

  • I iterate over the list and check if it is a time with regex. If it isn't I save it, to prepend it to the following items, and the append it to the output.

    Code:

    import re
    from pprint import pprint
    
    
    def forward(input_list):
        output = []
        for item in input_list:
            if not re.fullmatch(r"\d\d:\d\d", item):
                forwarded = item
            else:
                output.append(f"{forwarded} {item}")
        return output
    
    
    a = ["Today, 30 Dec",
         "01:10",
         "02:30",
         "Tomorrow, 31 Dec",
         "00:00",
         "04:30",
         "05:30",
         "01 Jan 2023",
         "01:00",
         "10:00"]
    
    b = forward(a)
    pprint(b)
    

    Output:

    ['Today, 30 Dec 01:10',
     'Today, 30 Dec 02:30',
     'Tomorrow, 31 Dec 00:00',
     'Tomorrow, 31 Dec 04:30',
     'Tomorrow, 31 Dec 05:30',
     '01 Jan 2023 01:00',
     '01 Jan 2023 10:00']