可能是 NumPy 数组元素访问错误?

问题描述 投票:0回答:1

我试图使用下面的代码在构造后修改

numpy
数组。 (是的,我知道有一些函数可以做到这一点,比如
np.random.randint(100, size=(2,3))
)。看起来使用Python风格语法读取没有问题,但我无法对ndarray进行更改。

这可能是一个错误吗?或者我们应该像大多数开发人员那样将其称为功能?

import random
import numpy as np

def print_data(arr):
    for row in arr:
        for col in row:
            print(f'{col}\t', end=' ')
        print()

# Both creation methods have the same bug     
##a = np.ndarray(shape=(2,3),dtype=int)
a = np.zeros((2,3), dtype=int)
print_data(a)
print()
for row in a:
    for cell in row:
        # cell was printed out
        cell = random.randrange(99)
        print(cell, end=' ')
    # row was not changed
    print(row)

print()
print_data(a)
print()

for row in a:
    for i in range(len(row)):
        row[i] = random.randrange(99)
        print(row[i], end=' ')
    print(row)
print()
print_data(a)

输出:

1    0   -447458960  
32763    -447580336  32763   

6 2 77 [         1          0 -447458960]
50 20 75 [     32763 -447580336      32763]

1    0   -447458960  
32763    -447580336  32763   

95 61 3 [95 61  3]
76 23 82 [76 23 82]

95   61  3   
76   23  82

如输出所示,第一个双循环打印出随机数没有任何问题。然而,矩阵元素没有被修改。在第二个代码块中,

a[i]
起作用了。我还测试了如果
a[i,j]
在双循环中使用它是否有效。

任何想法或详细解释的链接将不胜感激。

python numpy multidimensional-array
1个回答
0
投票

它按预期工作。要更改单个单元格,请使用

a[i,j] = ...

© www.soinside.com 2019 - 2024. All rights reserved.