[英]finding the closest value in a list
I'm trying to take a value from a list and find the closest value from another list, and sort it so it's the same.. I'm not good at explaining..我正在尝试从列表中获取一个值并从另一个列表中找到最接近的值,然后对其进行排序以使其相同.. 我不擅长解释..
here's my code:这是我的代码:
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 = []
What should i do / look up to do this?我应该怎么做/查找这样做? I've tried to google, but just can't find anything relevant
我试过谷歌,但找不到任何相关的东西
edit:编辑:
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]]
another edit: idk if it matters, but the lists are coordinates.另一个编辑:idk 是否重要,但列表是坐标。
you can sort first list indices base on the list values and use them to rearange the second list:您可以根据列表值对第一个列表索引进行排序,并使用它们重新排列第二个列表:
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
output:输出:
[[112, 112], [223, 223], [334, 334]]
You can try to use the sort() function ?您可以尝试使用 sort() 函数吗? :
:
list2 = [[223, 223], [112, 112], [334, 334]]
list2.sort()
Output:输出:
list2 = [[112, 112], [223, 223], [334, 334]]
Assuming the distance between tuples is measured by taking an absolute value of first element delta:假设元组之间的距离是通过取第一个元素 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.