Initializing 2D array in Python

后端 未结 3 1224
挽巷
挽巷 2020-12-01 15:23

I have a problem with initialzing a 2D array in python. I want a 6x6 array, I did

arr = [[None]*6]*6

But when I do:

>&g         


        
相关标签:
3条回答
  • 2020-12-01 15:27

    Using list comprehensions, you can say:

    arr = [[None for x in range(6)] for y in range(6)]
    

    Then you will have arr[1][2] = 10 working as expected. This is not a very normal thing to do, however. What are you going to use the nested lists for? There may be a better way. For example, working with arrays is made much easier with the numpy package.

    0 讨论(0)
  • 2020-12-01 15:44

    @Cameron is correct in suggesting that you use NumPy to deal with arrays of numerical data. And for the second part of your question, ~Niklas B. is spot on with his suggestion to use defaultdict.

    What hasn't been covered is why [[None]*6]*6 behaves strangely.

    The answer is that [None]*6 creates a list with six Nones in it (like you expect), but [list]*6 does not make six independent copies of list - it makes six copies of a reference to the same list.

    Idiomatic Python has a section that may explain this better: "Other languages have variables - Python has names".

    0 讨论(0)
  • 2020-12-01 15:50
    arr = [[None for i in range(6)] for j in range(6)]
    
    arr[1][2] = 10
    
    arr
    
    0 讨论(0)
提交回复
热议问题