Creating lists of lists in a pythonic way

后端 未结 8 2125
挽巷
挽巷 2021-02-08 06:18

I\'m using a list of lists to store a matrix in python. I tried to initialise a 2x3 Zero matrix as follows.

mat=[[0]*2]*3

However, when I chang

8条回答
  •  说谎
    说谎 (楼主)
    2021-02-08 07:02

    This one is faster than the accepted answer!
    Using xrange(rows) instead of [0]*rows makes no difference.

    >>> from itertools import repeat
    >>> rows,cols = 3,6
    >>> a=[x[:] for x in repeat([0]*cols,rows)]
    

    A variation that doesn't use itertools and runs around the same speed

    >>> a=[x[:] for x in [[0]*cols]*rows]
    

    From ipython:

    In [1]: from itertools import repeat
    
    In [2]: rows=cols=10
    
    In [3]: timeit a = [[0]*cols for _ in [0]*rows]
    10000 loops, best of 3: 17.8 us per loop
    
    In [4]: timeit a=[x[:] for x in repeat([0]*cols,rows)]
    100000 loops, best of 3: 12.7 us per loop
    
    In [5]: rows=cols=100
    
    In [6]: timeit a = [[0]*cols for _ in [0]*rows]
    1000 loops, best of 3: 368 us per loop
    
    In [7]: timeit a=[x[:] for x in repeat([0]*cols,rows)]
    1000 loops, best of 3: 311 us per loop
    

提交回复
热议问题