Creating lists of lists in a pythonic way

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

    This will work

    col = 2
    row = 3
    [[0] * col for row in xrange(row)]
    
    0 讨论(0)
  • 2021-02-08 06:40

    If the sizes involved are really only 2 and 3,

    mat = [[0, 0], [0, 0], [0, 0]]
    

    is easily best and hasn't been mentioned yet.

    0 讨论(0)
  • 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]]
    
    0 讨论(0)
  • 2021-02-08 06:52

    Use a list comprehension:

    >>> mat = [[0]*2 for x in xrange(3)]
    >>> mat[0][0] = 1
    >>> mat
    [[1, 0], [0, 0], [0, 0]]
    

    Or, as a function:

    def matrix(rows, cols):
        return [[0]*cols for x in xrange(rows)]
    
    0 讨论(0)
  • 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]]
    
    0 讨论(0)
  • 2021-02-08 06:58

    I use

    mat = [[0 for col in range(3)] for row in range(2)]
    

    although depending on what you do with the matrix after you create it, you might take a look at using a NumPy array.

    0 讨论(0)
提交回复
热议问题