python circulating delete the pit when the elements in this list! [turn]

 

Bowen original link: https://www.cnblogs.com/baihualin/p/10698651.html

Do not use positive sequence traversal cycle when deleting elements in the list, be sure to use anti-order traversal!

 

Ado, the first case the code:

Copy the code
def test(data):
    for i in data:
        data.remove(i)
    return data


data = [1, 2, 3]
print(test(data))
Copy the code


The face of the code above, at first glance thought it would print out an empty list, as in the test for function by way of the data elements are removed, it is not true, actual output is as follows:

[2]

 

 

Why would such a result? Let's analyze what depth:

In memory of the original list is:

The first time through the data.remove (i) the first element of '1' deleted, the list becomes:

When performing a second to data.remove (i) i is the second element, i.e., '3', then the '3' deleted, the list becomes:

The list of the third element has no, i.e. out of the loop of [2] to return.

 

 

How to solve this problem? We can use the method of reverse deleted!

Directly on the code:

Copy the code
def test(data):
    for i in data[::-1]:
        data.remove(i)
    return data


data = [1, 2, 3]
print(test(data))
Copy the code

At this point run, output is found empty list

[]

 

 

Delete reverse principle is as follows:

In memory of the original list is:

The first time through the data.remove (i) is the penultimate element of '3' deleted, the list becomes:

When the second execution data.remove (i) i is the penultimate element, i.e., '2', then the '2' deleted, the list becomes:

When the third execution to data.remove (i) i is the reciprocal of the third element, namely '1', then the '1' is deleted, the list becomes empty list!

 

 

Summary: positive sequence deleted in the list of elements, the values ​​behind the deletion of elements will top forward and lead to leakage deleted. When the reverse delete elements, the value of the front element does not delete lean back, it is possible to traverse the complete list of all the elements.

 

Guess you like

Origin www.cnblogs.com/lilinyuan5474/p/11655582.html