Python-如何避免for循环中缓冲区变量的依赖性



我想在python中实现一个非常简单的插入排序算法,在该算法中,我可以根据行/列的第n个元素按行/列对数组进行排序

A = [(2,1,2),(1,4,1),(3,2,3)]

变成

A = [(1,4,1),(2,1,2),(3,2,3)]

当按行排序和A[0]的依赖性时

所以我写了一个函数

import numpy as np
'''
Algorithm to sort array row/columnwise
A : numpy array, x : axis on which to sort (0:=rows, 1:=colums in 2D)
nth : nth element of array to sort
'''
def insertion_sort(A, x, nth):
if x == 0:
for i in range(1, np.size(A, axis=x)):
buffer = A[i]
j = i-1
while j >= 0 and A[j][nth] > buffer[nth]:
A[j+1] = A[j]
j -= 1
A[j+1] = buffer
return A

我用称之为

A = np.array([(2,1,2),(1,4,1),(3,2,3)])
print(insertion_sort(A,0,0))

但我遇到了一个错误,因为缓冲区随着行中i的依赖性而变化

buffer = A[i]

影响的因素

A[j+1] = buffer

在循环结束时。我真的不认为这应该发生吗?我错过什么了吗?该功能的输出为

[[2 1 2]
[2 1 2]
[3 2 3]]

这是错误的。

NumPy数组存储在连续的内存位置。因此,A[j+1] = A[j]不能通过复制存储器地址来完成(这样做会导致A[j+1]A[j]具有相同的地址),因此通过复制值来完成分配。

您可以使用print(buffer.__array_interface__['data'][0])检查buffer的内存位置

最新更新