python - Numpy 多维数组赋值未知登录错误

标签 python numpy

我很困惑为什么我在 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]]]
为什么?任何帮助表示赞赏。

最佳答案

虽然您希望代码将变量的值分配给新对象,但您的代码的解释方式有所不同:

引自 python standard library :

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/

相关文章:

python - 使用 fmin_slsqp 构造最小二乘函数

python-3.x - 如何使用包含 numpy.ndarrays 的列/列对 pandas 数据框执行 StandardScaler?

python - 使用 pandas 中 dataframe1 中某一列的值查找 dataframe2 中特定列的值

python - 如何在python中使用selenium定位四个元素

python findall 找不到正则表达式

python - 使用 py2exe 创建的 exe 不工作并返回有错误的日志文件

python - numpy polyfit 产生无意义的结果

python - 有没有办法在 python 中将 xml 子标签存储在列表中?

python - 在 keras 中绘制学习曲线给出 KeyError : 'val_acc'

python - 如何使用 NumPy.recarray 的两个 View 修改它