我有一个这样的列表:
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/