【发布时间】:2019-05-22 20:19:16
【问题描述】:
这是一个 Python 函数参数传递问题。 我想要一个 Python 函数来调整作为函数引用参数之一的 numpy 数组的大小。
传递的数组的内容似乎在函数内部和外部发生了变化。不知何故,数组对象的更新大小/形状没有从函数中导出,即使我认为 Python 通过引用传递参数。我是 Python 编程的新手,并希望通过引用来更新对象的所有方面。我是否需要明确“导出”更改?
#!/opt/local/bin/python2.7
# Function Test returning changed array
import numpy
def adjust( a1, a2 ) :
" Adjust passed arrays (my final function will choose which one to adjust from content) "
print str(a1.shape) + " At start inside function"
a1[-1,0] = 99
a1 = numpy.delete(a1, -1, 0)
print str(a1.shape) + " After delete inside function"
return None
d1 = numpy.array( [ [ 1, 2, 3],
[11, 12, 13],
[21, 22, 23],
[31, 32, 33] ] )
d2 = numpy.array( [ [ 9, 8, 7],
[19, 18, 17] ] )
print str(d1.shape) + " At start"
# Let us delete the last row
d1 = numpy.delete(d1, -1, 0)
print str(d1.shape) + " After delete"
# Worked as expected
# So far so good, now do it by object reference parameters in a function......
adjust( d1, d2 )
print d1
print str(d1.shape) + " After function delete return"
# Reference fails to update object properties
不知何故,引用的数组对象没有更新它的大小/形状属性。返回的数组中应该只有 2 行。
(4, 3) At start
(3, 3) After delete
(3, 3) At start inside function
(2, 3) After delete inside function
[[ 1 2 3]
[11 12 13]
[99 22 23]]
(3, 3) After function delete return
所以主线/全局代码按预期工作,该函数无法调整大小,但末尾现在删除的行显示了更新的数据。 记住最终函数会选择几个参数中的哪一个来调整,我如何从函数中完全导出参数的更改形状/大小?
【问题讨论】:
标签: python numpy function-parameter