gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 01:29:13 24 4
gpt4 key购买 nike

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com