The * operator in python has a special symbol "*" in python. it can be used as a multiplication operator for numerical operations and a repetition operator for objects, but you must pay attention to it when using it as a repeated operator.
Note: * repeated objects have the same id, that is, pointing to the same address in the memory. Be sure to perform operations on each object.
For example:
>>> alist = [range(3)]*4>>> alist[[0, 1, 2], [0, 1, 2], [0, 1, 2], [0, 1, 2]]
A list of two layers initialized above is used to simulate A matrix. The matrix type is 4x3, which is easy to describe. Here the matrix is.
Now I want to assign a value of 1 to A11 and use the following code:
1
Alist [0] [0] = 1
The expected result is:
1
[[1, 1, 2], [0, 1, 2], [0, 1, 2], [0, 1, 2]
Unfortunately, what we get is:
1
[[1, 1, 2], [1, 1, 2], [1, 1, 2], [1, 1, 2]
Why does this happen? why does it assign a value to A21? why does other Ai1 change?
The reason is as follows:
As we have already said at the beginning of this article, * repeated objects have the same id, that is, pointing to the same address in the memory. you must pay attention to the operations on each object.
We use the repeat operator "*" during reinitialization. when we repeat an object, this operator points all the repeated objects to the same memory address, when you change one of the values,
Other values will be updated. the following command and output are explained in python:
>>> id(alist[0])18858192>>> id(alist[1])18858192>>> id(alist[2])18858192>>> id(alist[3])18858192>>>
The IDs are all the same, that is, the four lists are the same "list ".
In this case, what should we do if we want to simulate a matrix? in addition to the dedicated numpy package, you can certainly append the new list to the upper list one by one, for example:
>>> blist=[]>>> for i in range(4): blist.append([j for j in range(3)])>>> blist[[0, 1, 2], [0, 1, 2], [0, 1, 2], [0, 1, 2]]
In this way, let's try the assignment operation above:
>>> blist[0][0]=1>>> blist[[1, 1, 2], [0, 1, 2], [0, 1, 2], [0, 1, 2]]>>>