这是一个很好的问题。我找不到任何可以接近您完全展开的解决方案的速度的东西(编辑 @BiRico 能够想出一些接近的东西。请参阅评论和更新:)。以下是我(和其他人)提出的一系列不同选项以及相关的时间安排:
import numpy as np
def f1():
"np.array + nested lists"
my_array = np.array([[1, 3], [2.4, -1]])
def f2():
"np.array + nested tuples"
my_array = np.array(((1, 3), (2.4, -1)))
def f3():
"Completely unrolled"
my_array = np.empty((2,2),dtype=float)
my_array[0,0] = 1
my_array[0,1] = 3
my_array[1,0] = 2.4
my_array[1,1] = -1
def f4():
"empty + ravel + list"
my_array = np.empty((2,2),dtype=float)
my_array.ravel()[:] = [1,3,2.4,-1]
def f5():
"empty + ravel + tuple"
my_array = np.empty((2,2),dtype=float)
my_array.ravel()[:] = (1,3,2.4,-1)
def f6():
"empty + slice assignment"
my_array = np.empty((2,2),dtype=float)
my_array[0,:] = (1,3)
my_array[1,:] = (2.4,-1)
def f7():
"empty + index assignment"
my_array = np.empty((2,2),dtype=float)
my_array[0] = (1,3)
my_array[1] = (2.4,-1)
def f8():
"np.array + flat list + reshape"
my_array = np.array([1, 3, 2.4, -1]).reshape((2,2))
def f9():
"np.empty + ndarray.flat (Pierre GM)"
my_array = np.empty((2,2), dtype=float)
my_array.flat = (1,3,2.4,-1)
def f10():
"np.fromiter (Bi Roco)"
my_array = np.fromiter((1,3,2.4,-1), dtype=float).reshape((2,2))
import timeit
results = {}
for i in range(1,11):
func_name = 'f%d'%i
my_import = 'from __main__ import %s'%func_name
func_doc = globals()[func_name].__doc__
results[func_name] = (timeit.timeit(func_name+'()',
my_import,
number=100000),
'\t'.join((func_name,func_doc)))
for result in sorted(results.values()):
print '\t'.join(map(str,result))
以及重要的时间:
在 Ubuntu Linux 上,Core i7:
0.158674955368 f3 Completely unrolled
0.225094795227 f10 np.fromiter (Bi Roco)
0.737828969955 f8 np.array + flat list + reshape
0.782918930054 f5 empty + ravel + tuple
0.786983013153 f9 np.empty + ndarray.flat (Pierre GM)
0.814703941345 f4 empty + ravel + list
1.2375421524 f7 empty + index assignment
1.32230591774 f2 np.array + nested tuples
1.3752617836 f6 empty + slice assignment
1.39459013939 f1 np.array + nested lists