Be wary of the *duplicate character (operator) in python

高洛峰
Release: 2016-10-18 09:58:27
Original
949 people have browsed it

There is a special symbol "*" in python, which can be used as a multiplication operator for numerical operations and also as a repetition operator for objects. However, you must pay attention when using it as a repetition operator

Note that: *Each repeated object has the same id, which means it points to the same address in the memory. You must pay attention when operating each object.

For example:

>>> alist = [range(3)]*4
>>> alist
[[0, 1, 2], [0, 1, 2], [0, 1, 2], [0, 1, 2]]
Copy after login

The above initializes a two-level list to simulate the matrix. The matrix is ​​4X3. For the convenience of description, the matrix is ​​denoted as A here.

Now I want to assign a value of 1 to A11, using the following code:

1

alist[0][0]=1

Then the result we want should be:

1

[[1, 1, 2], [0, 1, 2], [0, 1, 2], [0, 1, 2]]

But unfortunately , what we get is:

1

[[1, 1, 2], [1, 1, 2], [1, 1, 2], [1, 1, 2]]

What is going on? Why is the value assigned to A21, and why do other Ai1s change accordingly?


The reason is this:

We have already said it at the beginning of the article. * Each repeated object has the same id, which means it points to the same address in the memory. When operating on each object, Be sure to pay attention.

We used the repetition operator "*" when initializing. When this operator performs repeated operations on objects, all repeated objects will point to the same memory address. So when you change one of the values,

Other values ​​will naturally be updated. The explanation in python is the following command and output:

>>> id(alist[0])
18858192
>>> id(alist[1])
18858192
>>> id(alist[2])
18858192
>>> id(alist[3])
18858192
>>>
Copy after login

See, the ids are all the same, which means that these 4 lists are the same." list".

In this case, what should we do if we want to simulate a matrix? In addition to the special numpy package, you can of course append new lists 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]]
Copy after login

In this way, we can Try the assignment operation above:

>>> blist[0][0]=1
>>> blist
[[1, 1, 2], [0, 1, 2], [0, 1, 2], [0, 1, 2]]
>>>
Copy after login


source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!