import numpy
A = numpy.array([1,2,3,4,5,6,7,8,9,10])
B = numpy.array([1,2,3,4,5,6])
A[7:7+len(B)] = B # A[7:7+len(B)] has in fact length 3 !
我们得到这个典型错误:
ValueError: could not broadcast input array from shape (6) into shape (3)
这是100%正常的,因为A[7:7+len(B)]
的长度为3,和不是长度= len(B)
= 6,因此不能接收B!的内容!
如何防止这种情况发生,并具有B-复制到轻松的内容,开始A[7]
:
A[7:???] = B[???]
# i would like [1 2 3 4 5 6 7 1 2 3]
这可以被称为“自动播放”,即我们不不得不担心阵列的长度。
编辑:另一个例子,如果len(A) = 20
:
A = numpy.array([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20])
B = numpy.array([1,2,3,4,5,6])
A[7:7+len(B)] = B
A # [ 1 2 3 4 5 6 7 1 2 3 4 5 6 14 15 16 17 18 19 20]
我不得不阅读它两次,并进行测试,以实现它在所有情况下工作:)好的一行! – Basj
这利用了“A [7:1000]”与“A [7:]”一样好的事实。 – hpaulj