簡體   English   中英

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

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

我有幾個數字的列表。 我想使用插值將列表的大小增加 n 個數字。 我現有的代碼和 output:

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()

現有數據:

在此處輸入圖像描述

現有 output:

在此處輸入圖像描述

預期 output: 在此處輸入圖像描述

聽起來你想要一個線性關系,並在現有值之間插入新值。 我會寫一個 function 在兩個現有值之間的行上生成一些數字 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]

希望對您有所幫助,祝您編碼愉快!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM