Skip to main content
 首页 » 编程设计

python之填写列表中的缺失值

2024年09月07日8unruledboy

假设我有 2 个与时间戳和数字相关的数据列表:

list1 = ['00:00:02', '00:00:05', '00:00:06'] 
list2 = [2,3,4] 

我基本上想将缺少的时间戳填充到一天的剩余时间,并且在任何时候都有一个“0”,时间戳没有对应的数字,假设时间与数字 sin list1 和 list2 匹配。所以我们得到:

list1 = ['00:00:02', '00:00:05', '00:00:06'] 
list2 = [2,3,4] 
 
list3 = ['00:00:00', '00:00:01', '00:00:02', '00:00:03', '00:00:04', '00:00:05', '00:00:06'] 
list4 = [0,0,2,0,0,3,4] 

一直在尝试概念化如何做到这一点,但想不出任何合乎逻辑的事情。

请您参考如下方法:

您可以使用生成器生成每一对,而不是硬编码列表:

from functools import reduce 
 
def base60(ts): 
    """Parses the timestamps HH:MM:SS into monotonic integer numbers""" 
    return reduce(lambda acc, v: acc * 60 + int(v), ts.split(":"), 0)  
 
def to_ts(v): 
    """Convert a single integer representing a "base 60" HH:MM:SS timestamp into a timestamp sting""" 
    parts = [] 
    while v: 
        parts.insert(0, "{:02d}".format(v % 60)) 
        v //= 60 
    return ":".join((["00"] * (3 - len(parts))) + parts) 
 
def timeseries(timestamps, values): 
    counter = 0 
    for timestamp, value in zip(timestamps, values): 
        target = base60(timestamp) 
        while counter < target: 
            # While internal counter is less than the next 
            # timestamp in the given series,  
            # yield the counter and a value of zero.  
            yield to_ts(counter), 0 
            counter += 1 
        yield timestamp, value 
        counter += 1 

如果您确实需要将结果作为两个单独的静态序列(尽管 zip 产生元组而不是列表):

list3, list4 = zip(*timeseries(list1, list2))