numpy.append
,与Python的不同list.append
,没有执行到位的操作。因此,您需要将结果分配回变量,如下所示。
import numpy
xyz_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
nums = numpy.array([])
coords = numpy.array([])
for i in range(int(len(xyz_list)/4)):
nums = numpy.append(nums, xyz_list[i*4])
coords = numpy.append(coords, xyz_list[i*4+1:(i+1)*4])
print(nums) # [ 1. 5. 9.]
print(coords) # [ 2. 3. 4. 6. 7. 8. 10. 11. 12.]
你可以重塑coords
如下:
coords = coords.reshape(3, 3)
# array([[ 2., 3., 4.],
# [ 6., 7., 8.],
# [ 10., 11., 12.]])
更多详情请参阅numpy.append
行为
文档:
返回: arr 的副本,其值附加到轴上。注意
追加不会就地发生:分配并填充新数组。
如果你知道自己的形状numpy
预先数组输出,通过实例化是有效的np.zeros(n)
并稍后用结果填充它。
另一种选择:如果您的计算大量使用插入元素向左转的数组,考虑使用collections.deque来自标准库。