Python系列算法

标签 python algorithm list linear-interpolation

我有一个这样的列表:

numbers = [12, None, None, 17, 20, None, 28]

为了用适当的数字填充 None 值,以便 None 值获得定义值之间的数字,要考虑的最佳途径是什么。

示例:

numbers = [12, **14**, **16**, 17, 20, **24**, 28]

最佳答案

动态插值以创建线性插值:

def interpolate(l):
    last = None
    count = 0
    for num in l:
        if num is None:
            # count the number of gaps
            count += 1
            continue
        if count:
            # fill a gap based on the last seen value and the current
            step = (num - last) / float(count + 1)
            for i in xrange(count):
                yield last + int(round((1 + i) * step))
            count = 0
        last = num
        yield num

演示:

>>> list(interpolate([12, None, None, 17, 20, None, 28]))
[12, 14, 15, 17, 20, 24, 28]

关于Python系列算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27322496/

相关文章:

python - 在 seaborn.despine() 上动态设置轴偏移

python - 如何让 python 数据类继承 __hash__?

python - 检查当前行中的所有列值是否小于 pandas 数据框中的所有先前行

python - 物体发生了什么事?

python - 如何在python上获取周数?

php - YouTube 链接不提供视频 ID

algorithm - 普遍的哈希误解

java - 如何解决类型安全警告从 Collection 到 List<File> Java 6 的未经检查的强制转换而不使用抑制注释

Rbinding 大量数据帧

javascript - 使用 Javascript 在页面上保留运行列表