📜  如何使 NumPy 数组只读?

📅  最后修改于: 2022-05-13 01:54:22.956000             🧑  作者: Mango

如何使 NumPy 数组只读?

让我们讨论如何使 NumPy 数组不可变,即无法重写或无法更改。这可以通过将 NumPy 数组的可写标志设置为 false 来完成。

句法:

array.flags.writable=False

这将可写标志设置为假,因此数组变得不可变,即只读。请参阅下面的示例

例子:

Python
import numpy as np
 
 
a = np.zeros(11)
print("Before any change ")
print(a)
 
a[1] = 2
print("Before after first change ")
print(a)
 
a.flags.writable = False
print("After making array immutable on attempting  second change ")
a[1] = 7


输出:

Before any change
[0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
Before after first change
[0. 2. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
After making array immutable on attempting  second change
Traceback (most recent call last):
  File "gfg9.py", line 11, in 
    a[1]=7
ValueError: assignment destination is read-only