Home > Backend Development > Python Tutorial > Be wary of the *duplicate character (operator) in python

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

大家讲道理
Release: 2016-11-07 17:21:23
Original
1343 people have browsed it

There is a special symbol "*" in python, which can be used as a multiplication operator for numerical operations and 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:

alist[0][0]=1
Copy after login

Then the result we want should be:

[[1, 1, 2], [0, 1, 2], [0, 1, 2], [0, 1, 2]]
Copy after login

But unfortunately, what we get is:

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

What is going on? Why is A21 assigned a value? Why are other Ai1 What has changed?

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. You must pay attention when operating each object. .

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

As you can 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, let’s try again The above assignment operation:

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


Related labels:
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