You need to use a two-dimensional array in your program to find such a usage on the Web:
123456 |
#创建一个宽度为3,高度为4的数组 #[[0,0,0], # [0,0,0], # [0,0,0], # [0,0,0]] myList = [[ 0 ] * 3 ] * 4 |
But when operation mylist[0][1] = 1 o'clock, the entire second column is found to be assigned, which becomes
[[0,1,0],
[0,1,0],
[0,1,0],
[0,1,0]]
Why... The Python standard Library found the answer in the back.
List * N->n shallow copies of list concatenated, n a shallow copy of List of connections
Cases:
123456 |
>>> 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 and modifies any
An element will change the entire list:
So you need to create a multidimensional array in a different way to avoid shallow copying:
123456 |
>>> lists
=
[[]
for
i
in
range
(
3
)]
>>> lists[
0
].append(
3
)
>>> lists[
1
].append(
5
)
>>> lists[
2
].append(
7
)
>>> lists
[[
3
], [
5
], [
7
]]
|
The previous two-dimensional array was created in the following way:
1 |
myList = [([ 0 ] * 3 ) for i in range ( 4 )] |
Python's two-dimensional array operation