是否有可能比较2个列表中的值并从第三个列表中返回相似或最接近的值

问题描述 投票:0回答:1

我想在v中找到j的相似值并返回x。当j中的值不等于v时,我会喜欢该代码来检测j中介于v之间的2值。因此,如果j介于v1和v2之间,我希望代码返回max(x1,x2)-(((j-v1)/(v2-v1))*(max(x1,x2)-min(x1, x2)))

v= [100,200,300,400,500,600,700,800,900,1000,1100]
x= [67,56,89,21,90,54,38,93,46,17,75]
j= [200,300,400,460,500,600,700,800,870,900,950]

for i in range(len(v)-1):
    if v[i] > j and V[i+1] < j:
        p = max(x[i],x[i+1])- ( ((j-v[i])/(v[i+1]-v[i]))*(max(x[i],x[i+1])-min(x[i],x[i+1])))
    elif v[i] ==j:
        b= x[i]
print(p,b)

"""
n = [x[i] for i, v_ele in enumerate(v) if v_ele in j]
p=  [x[i] for i, v_ele in enumerate(v) if v_ele > j and v_ele 
print(n)
"""

我希望我的回答返回

[56,89,21,48.6,90,54,38,93,60.1,46,31.5]
python arrays list for-loop if-statement
1个回答
0
投票

我们可以使用以下两个帮助器功能来实现。请注意,我认为问题的预期输出中可能会存在一些错误。

代码:

def get_v_indx(j_ele, v):
    if j_ele in v:
        return v.index(j_ele)
    else:
        for i, ele in enumerate(v):
            if ele > j_ele:
                return i-1+(j_ele-v[i-1])/(ele-v[i-1])

def get_x_ele(i, x):
    try:
        return x[i]
    except TypeError:
        return x[int(i)] + (x[int(i)+1]-x[int(i)])*(i-int(i))

用法:

>>> [get_x_ele(get_v_indx(j_ele, v), x) for j_ele in j]
[56, 89, 21, 62.4, 90, 54, 38, 93, 60.1, 46, 31.5]

推荐问答