python - 在函数内连接 numpy 数组并返回它?

标签 python arrays numpy pass-by-reference

考虑以下程序,如何在函数内连接两个 numpy 数组并返回它

#!/usr/bin/env python
import numpy as np

def myfunction(myarray = np.zeros(0)):
    print "myfunction : before = ", myarray    # This line should not be modified
    data = np.loadtxt("test.txt", unpack=True) # This line should not be modified
    myarray = np.concatenate((myarray, data))
    print "myfunction : after = ", myarray     # This line should not be modified
    return                                     # This line should not be modified

myarray = np.array([1, 2, 3])
print "main : before = ", myarray
myfunction(myarray)
print "main : after = ", myarray

这段代码的结果是:

main : before =  [1 2 3]
myfunction : before =  [1 2 3]
myfunction : after =  [ 1.  2.  3.  1.  2.  3.  4.  5.]
main : after =  [1 2 3]

我想要:

main : before =  [1 2 3]
myfunction : before =  [1 2 3]
myfunction : after =  [ 1.  2.  3.  1.  2.  3.  4.  5.]
main : after =  [ 1.  2.  3.  1.  2.  3.  4.  5.]

如何修改提供的程序以获得预期结果(# This line Should not be Modified 标记的 4 行应保持不变)?

最佳答案

您应该返回值

像这样修改函数:

def myfunction(myarray = np.zeros(0)):
    print "myfunction : before = ", myarray    # This line should not be modified
    data = np.loadtxt("test.txt", unpack=True) # This line should not be modified
    concatenated = np.concatenate((myarray, data))
    print "myfunction : after = ", myarray     # This line should not be modified
    return  concatenated

然后你会得到这样的结果

result = myfunction(myarray)

关于python - 在函数内连接 numpy 数组并返回它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15206206/

相关文章:

python - Django:没有名为模型的模块

vb.net - 比较两个字符串 ArrayList

python - 检查两个 3D numpy 数组是否包含重叠的 2D 数组

python - 为什么 Python 正则表达式不能处理格式化的 HTML 字符串?

python - 在 Docker 容器中安装 OpenCV

python - "Vanilla"网络 python

javascript - 将json对象插入javascript中的有序数组

c - 如何在函数中声明数组并在C中调用该函数

Python:列表和 numpy 对象数组之间的区别

python - Cython:(为什么/何时)最好使用 Py_ssize_t 进行索引?