繁体   English   中英

在列表中找到最接近的值

[英]finding the closest value in a list

我正在尝试从列表中获取一个值并从另一个列表中找到最接近的值,然后对其进行排序以使其相同.. 我不擅长解释..

这是我的代码:

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 = []

我应该怎么做/查找这样做? 我试过谷歌,但找不到任何相关的东西

编辑:


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 是否重要,但列表是坐标。

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

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]]

您可以尝试使用 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]]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM