Python 使用插值将列表中元素的大小增加 n 个

Python increasing the size of elements in a list by n number using interpolation

我有几个号码的列表。我想使用插值将列表的大小增加 n 个数字。 我现有的代码和输出:

R_data = [10, 40, 40, 40, 15]
R_op = [random.choice(R_data) for i in range(100)]
plt.plot(R_op,'-s')
plt.show()

现有数据:

现有输出:

预期输出:

听起来您想要线性关系,并在现有值之间插入新值。我会编写一个函数来在两个现有值之间的线上生成一些 N 值,然后使用它和原始 R_data 中的所有间隔组成新列表。这样的事情应该可以解决问题:

def interpolate_pts(start, end, num_pts):
    """ Returns a list of num_pts float values evenly spaced on the line between start and end """
    interval = (float(end)-float(start)) / float(num_pts + 1)
    new_pts = [0] * num_pts
    for index in range(num_pts):
        new_pts[index] = float(start) + (index+1)*interval
    return new_pts

R_data = [10.0, 40.0, 40.0, 40.0, 15.0]
num_pts_to_add_between_data = 4
new_data = []
for index in range(len(R_data)-1):
    first_num = R_data[index]
    second_num = R_data[index+1]
    new_data.append(first_num)  # Put the 1st value in the output list
    new_pts = interpolate_pts(first_num, second_num, num_pts_to_add_between_data)
    new_data.extend(new_pts)
new_data.append(R_data[-1]). # Add the final value to the output list

>>> print(new_data)
[10.0, 16.0, 22.0, 28.0, 34.0, 40.0, 40.0, 40.0, 40.0, 40.0, 40.0, 40.0, 40.0, 40.0, 40.0, 40.0, 35.0, 30.0, 25.0, 20.0, 15.0]

希望对您有所帮助,编码愉快!