Creating lists of lists in a pythonic way

后端 未结 8 2134
挽巷
挽巷 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:01

    What about:

    m, n = 2, 3
    >>> A = [[0]*m for _ in range(n)]
    >>> A
    [[0, 0], [0, 0], [0, 0]]
    >>> A[0][0] = 1
    [[1, 0], [0, 0], [0, 0]]
    

    Aka List comprehension; from the docs:

    List comprehensions provide a concise way to create lists 
    without resorting to use of     
    map(), filter() and/or lambda. 
    The resulting list definition tends often to be clearer    
    than lists built using those constructs.
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题