简体   繁体   English

Python 根据阈值列出前向填充元素

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

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.如果您看到一个时间值,append 它到当前日期并将该值保存到新列表中。

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.如果不是,我保存它,将其添加到以下项目之前,并将 append 添加到 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: 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']

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简单地遍历你的数据并存储前面的字符串,如果当前元素包含一个冒号 append 它

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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