gpt4 book ai didi

Python系列算法

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:24:50 24 4
gpt4 key购买 nike

我有一个这样的列表:

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com