簡體   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