我很困惑为什么我在 numpy 数组上实现的冒泡排序将所有项设置为其中一项(我不知道哪一项数组太大)
数据类型为
...
[[1128 1026 1192 1023]]
[[ 771 195 858 196]]
[[ 953 1799 955 1738]]]
当我有一个 int 数组时,同样的算法可以完美地对其进行排序,
g = [i for i in range(10)]
for i in range(0,len(g)):
for j in range(0,len(g)):
if(g[i]>g[j]):
cnt = g[i]
g[i] = g[j]
g[j] = cnt
我认为我的问题是我不理解多维 numpy 数组元素分配,请解释为什么会出现这种情况:
lines = cv2.HoughLinesP(edges, rho, theta, threshold, np.array([]),
min_line_length, max_line_gap)
按每个项目的第二个元素排序
for i in range(0,len(lines)):
for j in range(0,len(lines)):
if(lines[i][0][1]<lines[j][0][1]):
cnt = lines[i][0]
lines[i][0] = lines[j][0]
lines[j][0] = cnt[/CODE]
现在数组是
[[[ 738 1831 867 1831]]
...
[[ 738 1831 867 1831]]
[[ 738 1831 867 1831]]
[[ 738 1831 867 1831]]]
为什么?任何帮助表示赞赏。
最佳答案
虽然您希望代码将变量的值分配给新对象,但您的代码的解释方式有所不同:
Assignment statements in Python do not copy objects, they create bindings between a target and an object. For collections that are mutable or contain mutable items, a copy is sometimes needed so one can change one copy without changing the other. This module provides generic shallow and deep copy operations (explained below).
我举了一个列表的例子:
a
被初始化为一个列表,其中一个元素的值为 9:
In [1]: a = [9]
现在
In [2]: b = a
虽然看起来您刚刚创建了一个与 a
具有相同值的对象,但这行代码实际上所做的是创建对 same
的引用> 对象。
因此,为 a
的第一个元素分配新值将更改底层对象:
In [3]: a[0] = 1
如果调用您为该对象指定的新名称,它仍然会引用该对象:
In [4]: b
Out[4]: [1]
为了避免不必要的行为,您应该使用copy
:
In [1]: import copy
In [2]: a = [9]
In [3]: b = copy.copy(a)
In [4]: a[0] = 1
In [5]: b
Out[5]: [9]
np.arrays
有一个 .copy() 方法,您可以像这样调用它,而无需导入副本:
a = np.array([1,2,3])
b = a.copy()
关于python - Numpy 多维数组赋值未知登录错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56045860/