Home > Net >  Python list forward fill elements according to thresholds
Python list forward fill elements according to thresholds

Time:12-31

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"]

CodePudding user response:

Looks like that list contains dates and times.

Any item that contains a space is a date value; otherwise it is a time value.

Iterate over the list. If you see a date value, save it as the current date. If you see a time value, append it to the current date and save that value the new list.

CodePudding user response:

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']

CodePudding user response:

How about:

    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 = []

    base = ""
    for x in a:
        if ":" in x:
            b.append(base   " "   x)
        else:
            base = x

    print(b)

simply iterate over your data and store the front string and if the current element contains a colon append it

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']

  • Related