我试图从一个列表中获取一个值,并从另一个列表中找到最接近的值,然后对其进行排序,以使它相同。.我不善于解释。.
这是我的代码:
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 = []
我应该怎么做/看起来要这样做?我曾尝试过Google,但找不到任何相关内容
编辑:
if list1 = [[1, 1], [2, 2]] and list2 = [[2, 2], [100, 100]]
newlist would be [[2,2], [100, 100]]
if list1 = [[2, 2], [1, 1]] and list2 = [[2, 2], [100, 100]]
newlist would be [[100, 100], [2, 2]]
另一种编辑:如果重要的话,请输入idk,但是列表是坐标。
答案 0 :(得分:1)
您可以基于列表值对第一个列表索引进行排序,并使用它们重新排列第二个列表:
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]]
答案 1 :(得分:0)
您可以尝试使用sort()函数吗? :
list2 = [[223, 223], [112, 112], [334, 334]]
list2.sort()
输出:
list2 = [[112, 112], [223, 223], [334, 334]]
答案 2 :(得分:0)
假定元组之间的距离是通过获取第一元素增量的绝对值来测量的:
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]]