Creating lists of lists in a pythonic way

后端 未结 8 2126
挽巷
挽巷 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.
    

提交回复
热议问题