python numpy数组追加在.py文件中不起作用,但在终端中起作用 [英] python numpy array append not working in .py file, but works in terminal
问题描述
我正在尝试使用 np.append 附加到一个 numpy 数组.
I am trying to append to a numpy array using np.append.
例如
a = np.array([1])
np.append(a, [2])
此代码在终端中运行良好(结果为 array([1, 2])),但是当我运行包含相同代码的 .py 文件时它不起作用.当我在附加 [2] 后打印 a 时,它仍然是 [1].
this code works well in terminal (the result is array([1, 2])), but it won't work when I run a .py file including the same code included in it. When I print a after appending [2], it would still be [1].
这是我的 test.py 文件的代码:
Here is the code for my test.py file:
import numpy as np
a = np.array([1])
print(a)
np.append(a, [2])
print(a)
这是用终端运行它的结果:
and this is the result of running it with terminal:
python test.py
[1]
[1]
没有错误的错误结果.有谁知道可能是什么问题?
Wrong result with no error. Does anyone know what could possibly be the problem?
推荐答案
import numpy as np
a = np.array([1])
print(a)
a = np.append(a, [2])
print(a)
numpy.append(arr, values, axis=None)
,其中 arr
是将值附加到该数组的副本(http://docs.scipy.org/doc/numpy-1.10.0/reference/generated/numpy.append.html).
numpy.append(arr, values, axis=None)
, where arr
is values are appended to a copy of this array (http://docs.scipy.org/doc/numpy-1.10.0/reference/generated/numpy.append.html).
在终端中你的代码可以工作,因为 np.append(a,[2])
变成了 print np.append(a,[2])
.
In terminal your code works because np.append(a,[2])
become print np.append(a,[2])
.
这篇关于python numpy数组追加在.py文件中不起作用,但在终端中起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!