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

swvgeqrz  于 2023-01-01  发布在  Python
关注(0)|答案(3)|浏览(110)

我列了一张单子

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

dtcbnfnu1#

我遍历这个列表,用正则表达式检查它是否是一个时间,如果不是,我保存它,把它添加到下面的项中,然后把它添加到输出中。
代码:

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)

输出:

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

dbf7pr2w2#

该列表似乎包含 * 日期 * 和 * 时间 *。
任何包含空格的项都是日期值;否则它是时间值。
遍历列表。如果看到日期值,将其保存为当前日期。如果看到时间值,将其附加到当前日期并将该值保存到新列表。

zbsbpyhn

zbsbpyhn3#

不如这样:

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)

只需遍历数据并存储前面的字符串,如果当前元素包含冒号,则追加它
输出:

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

相关问题