Python中一种有效的复数欧氏距离排序方法

2024-06-02 04:31:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我有几个复数,我需要根据它们的欧几里德距离排序。我是这样解决这个问题的:

            # A1x = Lowest Point (LP)
            # B1x = Point 1 (P1)
            # B4x = Point 2 (P2)

            C1 = euclidean(A1x, B1x) # Build the distance between LP and P1
            C4 = euclidean(A1x, B4x) # Build the distance between LP and P2

            array = np.array([C1, C4]) # Put the distances into an array...
            array.sort() # ...and sort it.

            # If the the distance between LP and P1 is the first element in the array
            # then take P1 as y_max value etc.

            if C1 == array[0]: 
                y_max = B1x

                if C4 == array[1]:
                    y_min = B4x

            if C4 == array[0]:
                y_max = B4x

                if C1 == array[1]:
                    y_min = B1x

这种方法对三到四个点很有效。但是,现在我得到了8到9个点,上面所说的方法有点讨厌,因为我必须为每一个点写if条件。因此,我想问你是否知道一种更好的方法来根据复数的欧几里德距离对它们进行排序。在


Tags: andtheifbetweenarraymaxdistancepoint
2条回答

使用argsort,这很简单:

Ap = np.array([1, 2]) # "lowest point"
B = np.array([[0,0], [1,1], [2,2], [3,3], [4,4]]) # sample array of points
dist = np.linalg.norm(B - Ap, ord=2, axis=1) # calculate Euclidean distance (2-norm of difference vectors)
sorted_B = B[np.argsort(dist)]

sorted_B最终包含列表B中的点,但按到点Ap的欧几里德距离排序。对于上面的输入,您将得到输出

^{pr2}$

注意,以这种方式使用NumPy函数应该比使用等效的Python函数list.sort更快、更高效。在

from functools import partial

complex_number_list.sort(key=partial(euclidean, A1x))

也可以使用abs代替euclidean。在

相关问题 更多 >