Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to solve the problem of trampling on Python list and dictionary

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)05/31 Report--

Most people do not understand the knowledge points of this article "how to solve the problem of trampling in Python list and dictionary", so the editor summarizes the following content, detailed content, clear steps, and has a certain reference value. I hope you can get something after reading this article. Let's take a look at this article, "how to solve the problem of trampling in Python list and dictionary".

First, about listing 1. Problem description

In Python, if you try to modify a set of data while traversing it, this is usually fine.

For example:

L = [3,4,56,7,10,9,6,5] for i in l: if not i% 2 = 0: continue l.remove (I) print (l)

The above code iterates through a list of numbers and modifies the list l directly in order to remove all even numbers.

However, the output after running is:

[3, 56, 7, 9, 5]

Wait a minute! The output seems to be wrong. The final result still contains an even number 56. Why didn't you successfully remove this number? We can try to print out all the elements that the for loop traverses

Run the following code:

L = [3,4,56,7,10,9,6,5] for i in l: print (I) if not i% 2 = 0: continue l.remove (I) print (l)

The output of this code is:

three

four

seven

ten

six

[3, 56, 7, 9, 5]

As you can see from the output, the for loop does not seem to have access to all the elements in the list. To understand what the for loop is doing internally, we can use iter and next to simulate it.

Taking a look at the following example, I used ipython shell to run the code:

In [1]: l = [3,4,56,7,10,9,6 5] In [2]: # turn the list into an iterator In [3]: it = iter (l) In [4]: # use the next () method to simulate the for loop In [5]: next (it) Out [5]: 3In [6]: next (it) Out [6]: 4In [7]: # remove an element already accessed by the iterator In [8]: l.remove (3) In [9]: Next (it) Out [9]: 7In [10]: # notice that 56 is skipped here We can remove another element In [11]: l.remove (4) In [12]: next (it) Out [12]: 9

The above experiment reveals that when you remove an element that has already been accessed by an iterator, in the next iteration, you skip one element on the right and go directly to the next one.

On the contrary, it still holds, that is, if you add an element at the beginning of the list after you start the iteration, you may access the element that has already been iterated in the next iteration.

This is what happens in the following code:

In [1]: l = [3,4,56,7,10,9,6,5] In [2]: it = iter (l) In [3]: next (it) Out [3]: 3In [4]: next (it) Out [4]: 4In [5]: l.insert (0,44) In [6]: next (it) Out [6]: 4

Note: when 44 is added to the header of the list, 4 is accessed twice.

two。 Solution

To solve the above problem, we have to make sure that the elements accessed by the iterator cannot be removed.

Option one

We can flip the original list to get a new list, then iterate over the new list, and remove the ineligible elements from the original list l.

The code of the scheme is as follows:

L = [3, 4, 56, 7, 10, 9, 6, 5] # list for i in reversed (l): print (I) if not i% 2 = 0: continue l.remove (I) print (l)

The results are as follows:

five

six

nine

ten

seven

fifty-six

four

three

[3, 7, 9, 5]

Note: the iterator now successfully accesses all the elements in the list and finally outputs a list that contains only odd numbers.

Option 2

We can also copy the list l before starting the iteration. But when there is too much data in list l, doing so obviously consumes performance.

The code of the scheme is as follows:

L = [3, 4, 56, 7, 10, 9, 6, 5] # use 'l.copy ()' here to make a shallow copy of list l for i in l.copy (): print (I) if not i% 2 = 0: continue l.remove (I) print (l)

The output is as follows:

three

four

fifty-six

seven

ten

nine

six

five

[3, 7, 9, 5]

This scheme ensures that the order of iteration is the same as that of removing elements. However, because the iterations and removals are for two different lists, it doesn't matter that the order is the same.

Second, about the dictionary 1. Problem description

When iterating over the dictionary, the dictionary cannot be modified. As follows:

# {0: 0,1: 1,2: 2,3: 3,4: 4,5: 5,6: 6,7: 7,8: 8,9: 9} d = {k: k for k in range (10)} for k, v in d.items (): if not v% 2 = 0: continue d.pop (k)

This code produces RuntimeError:

Traceback (most recent call last): File "F:/Documents/pythonprojects/01practice/app.py", line 7, in for k, v in d.items (): RuntimeError: dictionary changed size during iteration2. Solution

We can first copy all the key of the dictionary and then remove the elements that do not meet the criteria in the process of iterating through the key. The process is as follows:

# {0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8 9: 9} d = {k: k for k in range (10)} # here all the key values in the dictionary are copied # not the entire dictionary # while using tuple () faster for k in tuple (d.keys (): if not d [k]% 2 = 0: continue d.pop (k) print (d)

The output after running the code is as follows:

{1: 1, 3: 3, 5: 5, 7: 7, 9: 9}

We successfully removed all even key-value pairs from the dictionary!

The above is about the content of this article on "how to solve the problem of trampling on Python lists and dictionaries". I believe we all have a certain understanding. I hope the content shared by the editor will be helpful to you. If you want to know more related knowledge, please pay attention to the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report