Python 在列表中查找最接近的值

Python 在列表中查找最接近的值,python,list,loops,sorting,Python,List,Loops,Sorting,我试图从一个列表中获取一个值,从另一个列表中找到最接近的值,并对其进行排序,使其相同。。我不善于解释 这是我的密码: list1 = [[111, 111], [222, 222], [333, 333]] list2 = [[223, 223], [112, 112], [334, 334]] #I need to find the closest value, and put list 2 in same order as list1 #i Want newlist to be [[[112

我试图从一个列表中获取一个值,从另一个列表中找到最接近的值,并对其进行排序,使其相同。。我不善于解释

这是我的密码:

list1 = [[111, 111], [222, 222], [333, 333]]
list2 = [[223, 223], [112, 112], [334, 334]]
#I need to find the closest value, and put list 2 in same order as list1
#i Want newlist to be [[[112, 112], [223, 223], [334, 334]]
newList = []
我应该怎么做/向上看才能做到这一点?我试着用谷歌搜索,但就是找不到任何相关的东西

编辑:


另一个编辑:idk,如果有关系,但列表是坐标。

您可以尝试使用sort()函数:

    list2 = [[223, 223], [112, 112], [334, 334]]

    list2.sort()
输出:

    list2 = [[112, 112], [223, 223], [334, 334]]

假设元组之间的距离是通过获取第一个元素delta的绝对值来测量的:

import numpy as np
[list2[i] for i in [np.argmin([np.abs(l2[0]-l1[0]) for l2 in list2]) for l1 in list1]]

您可以根据列表值对第一个列表索引进行排序,并使用它们重新设置第二个列表的范围:

list1 = [[222, 222], [111, 111], [333, 333]]
list2 = [[223, 223], [112, 112], [334, 334]]

idx = sorted(range(len(list1)), key=lambda i: list1[i])

newList = [list2[i] for i in idx]
newList
输出:

[[112, 112], [223, 223], [334, 334]]

list(map(sorted,list2))
[list2中lst的sorted(lst)]
?一个问题:假设
list1=[[1,1],[2,2]]]
list2=[2,2],[100100]
。这方面的预期产出是什么<代码>[[2,2],[2,2]]或
[[2,2],[100100]
?请将此添加到您的问题中。如果
list1=[[1,4],[2,3]]
list2=[[1,-4],-2,-3]]
,这不会否定他们给出的示例,是的,这很有效。然而,我怀疑他们的问题是否如此简单,因为如果没有对
list1
进行排序,那么预期的输出也不会被排序是的,我简化了列表,它们实际上更长,并且不像这些列表那样按顺序排列。
[[112, 112], [223, 223], [334, 334]]