Posted in Http://liamchzh.0fees.net/?p=234&i=1
An accidental opportunity to find the list in Python very interesting.
Look at a piece of code first
[PY]
Array = [0, 0, 0]
Matrix = [Array*3]
Print matrix
# # [[0,0,0,0,0,0,0,0,0]][/py]
This code does not actually create a two-dimensional array
Look at the code again.
[PY]
Array = [0, 0, 0]
Matrix = [Array] * 3
Print matrix
# # [[0, 0, 0], [0, 0, 0], [0, 0, 0]][/py]
At first glance, this code should create a two-dimensional array.
Test it.
[PY]
MATRIX[0][1] = 1
Print matrix
# # [[0, 1, 0], [0, 1, 0], [0, 1, 0]][/py]
Supposedly matrix[0][1] should be modified to be just one element in a two-dimensional array, but the test results show that the second element of each list is modified.
Look at the documentation, then I found the Python standard Library
One of the 5.6 Sequence types is described in this way:
Note also that the copies is shallow; nested structuresis not copied. This often haunts new Python programmers; Consider:
>>> lists = [[]] * 3
>>> lists
[[], [], []]
>>> Lists[0].append (3)
>>> lists
[3], [3], [3]]
What have happened is this [[]] is a one-element list containing an empty list, so all three elements of [[]] * 3 are (poin Ters to) the single empty list. Modifying any of the elements of lists modifies this single list. You can create a list of different lists this by:
>>>
>>> lists = [[] for I in range (3)]
>>> Lists[0].append (3)
>>> Lists[1].append (5)
>>> Lists[2].append (7)
>>> lists
[3], [5], [7]]
That is, the Matrix = [Array] * 3 operation, only creates 3 references to the array, so once the array is changed, 3 lists in the matrix will change as well.
So how do you create a two-dimensional array in python?
For example, create an array of 3*3
Method 1 directly defines
[Py]matrix = [[0, 0, 0], [0, 0, 0], [0, 0, 0]][/py]
Method 2 indirectly defines
Matrix = [[0 for I in a range (3)] for I in range (3)]
Report:
My test code
Reference:
Python's two-dimensional array operation
StackOverflow
Defining a two-dimensional array in Python