2

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

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

4

2 回答 2

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)
于 2013-03-04T16:35:16.407 回答
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则会出现分段错误...

如果您没有设置refcheckFalse那将不会发生,但它也不会让您在函数内部进行修改。所以是的,它可以做到,但你不应该这样做:遵循 Entropiece 的方法。

于 2013-03-04T18:27:52.610 回答