考虑以下程序,如何在函数内连接两个 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/