Road Python learning: that something on the list (List) copied

To talk copy of the list, we will talk about Python assignment rules

 

First we create a list of a:

a=[1,2,3]

Usually we copy an element method is this:

= B A              # copy element general procedure

 Print (A)
 Print (B) 

the result is: 
[ 2,3 ] 
[ 2,3]

By this line of code, we of course have created a list with the equivalent list a b, but this time it will be a problem :

When we try to create a new list of b when sorting operations (such as reverse operation):

b.reverse () 

Print (B) 

the result is: 
[ 3,2,1]

Everything here seems nothing wrong, but in reality pit father thing has quietly ~

Let us try to print it lists a value of :

Print (A) 

results: 
[ 3,2,1]

Can see a list of a sort also changed the

This is not necessarily the result we want to see

The reason for this is:

When we use the "b = a" code to assign this list b, b and list is a list point to the same address, and to sort the list operation does not assign a new address list, that this whether we are on a list or sort operation on the list b, ordering another list will change

And if we do an assignment or if the list for a list of b, then there is no such concerns, because when the assignment list is assigned a new address

 

So how do we solve this problem?

Very simple, just use the list of fragments using the following code listing the copy operation:

= A [2,3 ] 
B = A [:]          # replication list right way

 Print (A)
 Print (B) 

the result is: 
[ 2,3 ] 
[ 2,3]

At this point we'll be on the list b reverse operation:

b.reverse () 

Print (A)
 Print (B) 

the result is: 
[ 2,3 ] 
[ 3,2,1]

Only you can see a list of b sort of change, and a list of the sort has not changed, it is because the list of a list of b and has no kind of helpless and tangled fetters of ( Ya Ya ◡

 

Guess you like

Origin www.cnblogs.com/toxic-antidote/p/11409151.html