跟进你的评论:
>>> import numpy >>> a = numpy.array(range(9)).reshape((3,3)) >>> b = numpy.zeros(tuple(s+2 for s in a.shape), a.dtype) >>> b[tuple(slice(1,-1) for s in a.shape)] = a >>> b array([[0, 0, 0, 0, 0], [0, 0, 1, 2, 0], [0, 3, 4, 5, 0], [0, 6, 7, 8, 0], [0, 0, 0, 0, 0]])
这是一个不太通用但易于理解的Alex的答案版本:
>>> a = numpy.array(range(9)).reshape((3,3)) >>> a array([[0, 1, 2], [3, 4, 5], [6, 7, 8]]) >>> b = numpy.zeros(a.shape + numpy.array(2), a.dtype) >>> b array([[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]) >>> b[1:-1,1:-1] = a >>> b array([[0, 0, 0, 0, 0], [0, 0, 1, 2, 0], [0, 3, 4, 5, 0], [0, 6, 7, 8, 0], [0, 0, 0, 0, 0]])