用数学公式对二维阵列排序

2024-03-29 15:34:34 发布

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

我有一个包含(x,y)的2D数组列表,但是我想用(x^2+y^2)的平方根的最小值对这个列表进行排序。你知道吗

例如,我有四个2D列表:

(20,10)
(3,4)
(5,6)
(1.2,7)

如果我取此列表中每个2D数组的平方根并返回排序列表的最小值,则输出为:

(3,4)
(1.2,7)
(6.5,4)
(5,6)
(20,10)

代码:

M=[ [20,10],[3,4],[5,6],[1.2,7],[6.5,4]]

s码=np.sqrt公司(米)

a=[]

打印s

对于范围(0,h)内的i:

  for j in range(0,w):

     a[i] =s[i][j]+a[i]

有什么想法吗?你知道吗


Tags: 代码in列表for排序np公司range
3条回答

使用列表的内置排序方法:

from math import sqrt

def dist(elem):
    return sqrt(pow(elem[0], 2) + pow(elem[1], 2))

def sorting_func(first, second):

    if dist(first) < dist(second):
        return 1
    elif dist(second) < dist(first):
        return -1
    else:
        return 0

bla= [(3, 2), (5, 4)]

bla.sort(sorting_func)

print bla

将数据结构切换到元组列表,然后使用最小值作为关键函数进行排序(使用memoization以提高效率):

M = [(20, 10), (3, 4), (5,6), (1.2, 7), (6.5, 4)]

def minimum_value(coordinate, dictionary={}):  # intentional dangerous default value
    if coordinate not in dictionary:
        dictionary[coordinate] = coordinate[0]**2 + coordinate[1]**2

    return dictionary[coordinate]

M_sorted = sorted(M, key=minimum_value)

print(M_sorted)

输出

[(3, 4), (1.2, 7), (6.5, 4), (5, 6), (20, 10)]

因为我们只是排序,我们不需要计算平方根,平方就足够了。你知道吗

下面的代码将解决您的要求,取消对print语句的注释,如果您想了解排序的工作原理!!你知道吗

import math
array = [(20,10), (3,4), (5,6), (1.2,7)]
sortList = []
count = 0
tempList = []
placeholder = []
#Compute the Equation of Minimum Value
for x,y in array:
    tempList.append(math.sqrt((x**2) + (y**2)))
    tempList.append(array[count])
    sortList.append(tempList)
    tempList = []
    count += 1
#Sort list
count = 1
placeholder  = sortList[0][:]
##print('ORIGINAL LIST\n', sortList)
while count < (len(sortList)):
    if sortList[count - 1][0] < sortList[count][0]:
##        print('THIS IS COUNT', count)
        count += 1
    else:
        placeholder = sortList[count - 1][:]
##        print("this is placeholder: ", placeholder)
        sortList[count - 1] = sortList[count]
##        print(sortList)
        sortList[count] = placeholder
##        print(sortList)
        placeholder = []
        count = 1

相关问题 更多 >