这显示了在numpy中填充未知大小数组的相当高的性能(尽管比初始化为精确大小慢):data = numpy.zeros( (1, 1) )
N = 0
while True:
row = ...
if not row: break
# assume every row has shape (K,)
K = row.shape[0]
if (N >= data.shape[0]):
# over-expand: any ratio around 1.5-2 should produce good behavior
data.resize( (N*2, K) )
if (K >= data.shape[1]):
# no need to over-expand: presumably less common
data.resize( (N, K+1) )
# add row to data
data[N, 0:K] = row
# slice to size of actual data
data = data[:N, :]
适应您的情况:if count > temp.shape[0]:
temp.resize( (max( temp.shape[0]*2, count+1 ), temp.shape[1]) )
if i > temp.shape[1]:
temp.resize( (temp.shape[0], max(temp.shape[1]*2, i+1)) )
# now safe to use temp[count, i]
您可能还需要跟踪实际的数据大小(max count,max i)并稍后修剪数组。