python - 填写列表中的缺失值

标签 python

假设我有 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))

关于python - 填写列表中的缺失值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50161316/

相关文章:

python - 如何找到张量A的元素在另一个张量中的索引?

python - 为 Python 包和模块使用短名称有多重要?

python - 根据日期间隔将数据填充到时间序列中

python - 选择具有最大值的列表

python - 在 python 中拆分项目并附加一些项目

python - 如何避免 django "clashes with related m2m field"错误?

python - "ConnectionResetError"我该怎么办?

python - 区分 WSGI 应用程序中的调试环境和生产环境

python - Django '<object> matching query does not exist' 当我在数据库中看到它时

python - 如何在 Spyder/IPython/matplotlib 中再次获得交互式绘图?