2d array of zeros

后端 未结 3 1971
眼角桃花
眼角桃花 2020-12-13 13:11

There is no array type in python, but to emulate it we can use lists. I want to have 2d array-like structure filled in with zeros. My question is: what is the difference, if

相关标签:
3条回答
  • 2020-12-13 13:17

    You should use numpy.zeros. If that isn't an option, you want the first version. In the second version, if you change one value, it will be changed elsewhere in the list -- e.g.:

    >>> a = [[0]*10]*10
    >>> a
    [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]
    >>> a[0][0] = 1
    >>> a
    [[1, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 0, 0, 0]]
    

    This is because (as you read the expression from the inside out), you create a list of 10 zeros. You then create a list of 10 references to that initial list of 10 zeros.


    Note that:

    zeros = [ [0]*M for _ in range(N) ]  # Use xrange if you're still stuck in the python2.x dark ages :).
    

    will also work and it avoids the nested list comprehension. If numpy isn't on the table, this is the form I would use.

    0 讨论(0)
  • 2020-12-13 13:30

    for Python 3 (no more xrange), the preferred answer

    zeros = [ [0] * N for _ in range(M)]
    

    for M x N array of zeros

    0 讨论(0)
  • 2020-12-13 13:34

    In second case you create a list of references to the same list. If you have code like:

    [lst] * N
    

    where the lst is a reference to a list, you will have the following list:

    [lst, lst, lst, lst, ..., lst]
    

    But because the result list contains references to the same object, if you change a value in one row it will be changed in all other rows.

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