Creating lists of lists in a pythonic way

后端 未结 8 2143
挽巷
挽巷 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 06:54

    Try this:

    >>> cols = 6
    >>> rows = 3
    >>> a = [[0]*cols for _ in [0]*rows]
    >>> a
    [[0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0]]
    >>> a[0][3] = 2
    >>> a
    [[0, 0, 0, 2, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0]]
    

    This is also discussed in this answer:

    >>> lst_2d = [[0] * 3 for i in xrange(3)]
    >>> lst_2d
    [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
    >>> lst_2d[0][0] = 5
    >>> lst_2d
    [[5, 0, 0], [0, 0, 0], [0, 0, 0]]
    

提交回复
热议问题