我有几个复杂的数字,我需要根据它们的欧氏距离进行排序。我这样解决了这个问题:
# 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条件。因此,我想问你是否知道一种更好的方法来按照欧几里德距离对复数进行排序。
答案 0 :(得分:2)
from functools import partial
complex_number_list.sort(key=partial(euclidean, A1x))
您也可以使用abs
代替euclidean
。
答案 1 :(得分:1)
使用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
array([[1, 1],
[2, 2],
[0, 0],
[3, 3],
[4, 4]])
最终包含列表B的点,但是按照欧几里德距离到点Ap的排序顺序。对于上面的输入,你将得到输出
list.sort
请注意,使用NumPy函数比使用等效的Python函数for name, places in favorite_places.items():
print("{}'s favorite places are:".format(name.capitalize()))
for city, country in places.items():
print("{} in {}.".format(city.capitalize(), country.capitalize()))
print('\n')
更快更有效。