This article mainly introduces some Python two-dimensional array operation method, is the basic knowledge of Python learning, need friends can refer to the
You need to use a two-dimensional array in your program, and find one on the web that uses:
?
1 2 3 4 5 6 |
#创建一个宽度为3, array of height 4 #[[0,0,0], # [0,0,0], # [0,0,0], # [0,0,0]] myList = [[0] * 3] * 4 |
But when the operation mylist[0][1] = 1 o'clock, it is found that the entire second column is assigned, and becomes
?
1 2 3 4 5 6 7 |
[[0,1,0], [0,1,0], [0,1,0], [0,1,0]] |
Why... I don't understand, back to the Python Standard Library to find the answer
List * N->n shallow copies of list concatenated, the connection of a shallow copy of n list
Cases:
?
1 2 3 4 5 6 |
>>> lists = [[]] * 3 >>> lists [[], [], []] >>> lists[0].append (3) >>> lists [[3], [3] , [3]] |
[[]] is a list containing an empty list element, so [[]]*3 represents 3 references to this empty list element, modifying any
An element changes the entire list:
So you need to create multidimensional arrays in a different way to avoid shallow copies:
?
1 2 3 4 5 6 |
>>> lists = [[] for I in range (3)] >>> lists[0].append (3) >>> Lists[1].append (5) >>> L Ists[2].append (7) >>> lists [[3], [5], [7]] |
The previous two-dimensional array was created in the following ways:
?
1 |
myList = [ ([0] * 3) for I in range (4)] |