你可以试试这个:
>>> import numpy as np
>>> class A:
... def __init__(self, values):
... self.partposit = values
...
>>> PARTS = dict((index, A(np.zeros((50000, 12)))) for index in xrange(163))
>>> p1 = np.dstack((PARTS[k].partposit for k in sorted(PARTS.keys())))
>>> p1.shape
(50000, 12, 163)
>>>
花了几秒钟把它堆在我的机器上。
>>> import timeit
>>> timeit.Timer('p1 = np.dstack((PARTS[k].partposit for k in sorted(PARTS.keys())))', "from __main__ import np, PARTS").timeit(number = 1)
2.1245520114898682
numpy.dstack
接收一系列数组并将它们堆叠在一起,因此如果我们只给它列表而不是自己连续堆叠它们会更快。
numpy.dstack(tup)
按顺序深度(沿第三轴)堆叠数组。获取一系列数组并将它们沿第三轴堆叠以形成单个数组。
http://docs.scipy.org/doc/numpy/reference/generated/numpy.dstack.html
我也很好奇你的方法会持续多久:
>>> import timeit
>>> setup = """
... import numpy as np
... #PARTS is my dictionary
... #the .partposit is the attribute that is an array of shape (50000, 12)
...
... class A:
... def __init__(self, values):
... self.partposit = values
...
... PARTS = dict((index, A(np.zeros((50000, 12)))) for index in xrange(163))
... ks = sorted(PARTS.keys())
... """
>>> stack = """
... p1 = PARTS[ks[0]].partposit
... for k in ks[1:]:
... p1 = np.dstack((p1, PARTS[k].partposit))
... """
>>> timeit.Timer(stack, setup).timeit(number = 1)
67.69684886932373
哎哟!
>>> numpy.__version__
'1.6.1'
$ python --version
Python 2.6.1
我希望这有帮助。