连接函数内的numpy数组并返回它?

时间:2013-03-04 16:26:39

标签: 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行应保持不变)?

2 个答案:

答案 0 :(得分:2)

您应该返回值

修改类似的功能:

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)

答案 1 :(得分:1)

您可以执行以下操作,但它可能会出错:

def in_place_concatenate(arr1, arr2) :
    n = len(arr1)
    arr1.resize((n + len(arr2),), refcheck=False)
    arr1[n:] = arr2

正如您所料:

>>> a = np.arange(10)
>>> b = np.arange(4)
>>> in_place_concatenate(a, b)
>>> a
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3])

可是:

>>> a = np.arange(10)
>>> b = np.arange(4)
>>> c = a[:5]
>>> c
array([0, 1, 2, 3, 4])
>>> in_place_concatenate(a, b)
>>> a
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3])
>>> c
array([         1, 1731952544,   71064376,          1,   67293736])

如果您尝试修改c中的任何数据,则会出现分段错误...

如果你没有将refcheck设置为False那不会发生,但它也不允许你在函数内部进行修改。所以是的,它可以完成,但你不应该这样做:遵循Entropiece的方法。