Creating lists of lists in a pythonic way

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

    Is there anything itertools can't do? :)

    >>> from itertools import repeat,izip
    >>> rows=3
    >>> cols=6
    >>> A=map(list,izip(*[repeat(0,rows*cols)]*cols))
    >>> 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]]
    

提交回复
热议问题