Python:创建一个包含 n 个列表的列表的最快方法 [英] Python: fastest way to create a list of n lists
问题描述
所以我想知道如何最好地创建一个空白列表:
So I was wondering how to best create a list of blank lists:
[[],[],[]...]
由于 Python 如何处理内存中的列表,这不起作用:
Because of how Python works with lists in memory, this doesn't work:
[[]]*n
这确实创建了 [[],[],...]
但每个元素都是同一个列表:
This does create [[],[],...]
but each element is the same list:
d = [[]]*n
d[0].append(1)
#[[1],[1],...]
类似于列表理解的东西:
Something like a list comprehension works:
d = [[] for x in xrange(0,n)]
但这使用 Python VM 进行循环.有没有办法使用隐式循环(利用它是用 C 编写的)?
But this uses the Python VM for looping. Is there any way to use an implied loop (taking advantage of it being written in C)?
d = []
map(lambda n: d.append([]),xrange(0,10))
这实际上更慢.:(
推荐答案
可能是唯一比
d = [[] for x in xrange(n)]
是
from itertools import repeat
d = [[] for i in repeat(None, n)]
它不必在每次迭代中都创建一个新的 int
对象,并且在我的机器上快了大约 15%.
It does not have to create a new int
object in every iteration and is about 15 % faster on my machine.
编辑:使用 NumPy,您可以使用
Edit: Using NumPy, you can avoid the Python loop using
d = numpy.empty((n, 0)).tolist()
但这实际上比列表理解慢 2.5 倍.
but this is actually 2.5 times slower than the list comprehension.
这篇关于Python:创建一个包含 n 个列表的列表的最快方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!