当进行以下操作时:
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)
这是完全正常的,因为
A[7:7+len(B)]
的长度为3,而不是长度=len(B)
=6,因此无法接收B的内容!如何防止这种情况发生,并轻松地将B的内容复制到A中,从
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]
A[7:1000]
和A[7:]
一样好的事实。 - hpaulj