Python 将一个列表的值替换为另一个列表中最接近的值

Python 将一个列表的值替换为另一个列表中最接近的值,python,list,replace,compare,Python,List,Replace,Compare,我有两份清单: list_1= [123, 122, 524, 500, 515, 600, 620] list_2= [120, 150, 500, 550, 600, 650] 我想用列表_2中最接近的值替换列表_1中的值,结果如下所示: new_list= [120,120,500,500,500,600,600] 如果能得到一些帮助就太好了 我是python新手,我正在尝试找到类似的解决方案。我的逻辑是: for j in list_2: for i in enumerate(lis

我有两份清单:

list_1= [123, 122, 524, 500, 515, 600, 620]
list_2= [120, 150, 500, 550, 600, 650]
我想用列表_2中最接近的值替换列表_1中的值,结果如下所示:

new_list= [120,120,500,500,500,600,600]
如果能得到一些帮助就太好了

我是python新手,我正在尝试找到类似的解决方案。我的逻辑是:

for j in list_2:
for i in enumerate(list_1):
    if j==i: (here I would need a conditional to say if it is close to value j)
一个想法是将列表_2中的值j从列表_1中的值i中减去,如果结果小于50,它将用j替换i,否则它将返回i

我是如何写的(到目前为止没有成功):


如果我发布了您当前的代码,请点击这里!我希望它能让我知道我在做什么。但还是个初学者。。
 if i-j<=50 :
    list_1[i]= list[i].replace(j,i)

 else:
    return i
list_1= [123, 122, 524, 500, 515, 600, 620]
list_2= [120, 150, 500, 550, 600, 650]
new_list = list_1[:]
for i, v in enumerate(list_1):
    ok = []
    for j, k in enumerate(list_2):
        ok.append(abs(v-k))
    # find the index of the closet element from list_2 to the current v
    ind = ok.index(min(ok))
    new_list[i] = list_2[ind]
print(new_list)

#[120, 120, 500, 500, 500, 600, 600]