Python: fastest way to create a list of n lists

前端 未结 5 631
温柔的废话
温柔的废话 2020-11-28 20:37

So I was wondering how to best create a list of blank lists:

[[],[],[]...]

Because of how Python works with lists in memory, this doesn\'t

5条回答
  •  孤城傲影
    2020-11-28 21:35

    The probably only way which is marginally faster than

    d = [[] for x in xrange(n)]
    

    is

    from itertools import repeat
    d = [[] for i in repeat(None, n)]
    

    It does not have to create a new int object in every iteration and is about 15 % faster on my machine.

    Edit: Using NumPy, you can avoid the Python loop using

    d = numpy.empty((n, 0)).tolist()
    

    but this is actually 2.5 times slower than the list comprehension.

提交回复
热议问题