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

What is the function of generator generator in Python

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

What is the role of generator generator in Python? I believe many inexperienced people don't know what to do about it. Therefore, this paper summarizes the causes and solutions of the problem. Through this article, I hope you can solve this problem.

Iteration, iterable, iterator

Iteration (iteration): iteration in python is usually done through for...in... To realize it. And as long as it is an iterable object iterable, it can be iterated.

Iterable object (iterable): any object in Python that defines a _ _ iter__ method that returns an iterator or a _ _ getitem _ _ method that supports subscript indexes. To put it simply, an iterable object is any object that can provide an iterator. An iterator object is returned. Official explanation

Iterator: simply put, an iterator is an object that implements iterator.__iter__ () and iterator.__next__ (), and the iterator.__iter__ () method returns the iterator object itself. According to the official statement, it is this method that implements for. In... Sentence. Iterator.__next__ () is the key that distinguishes iterator from iterable. It allows us to get an element explicitly. When the next () method is called, two operations are actually generated:

Update the iterator status to point to the next item, so that the next call, after each value, the pointer moves to the next bit, after traversing the iterator, it becomes an empty container, but not None, it should be noted that after the end of the iteration, the pointer will not automatically return to the first position, but still stay at the end position, in order to start, you need to reload the iterative object.

Example understanding:

> > from collections import Iterable, Iterator > a = [1je 2je 3] # it is well known that list is an iterable > b = iter (a) # through the iter () method, we get that iterator,iter () actually called _ iter__ (), > > isinstance (a, Iterable) True > isinstance (a, Iterator) False > > isinstance (b, Iterable) True > > isinstance (b, Iterator True)

It can be seen that itertor must be iterable, but iterable is not necessarily itertor

> dir (a) ['_ _ add__','__class__','__contains__','__delattr__','__delitem__','__dir__','__doc__','__eq__','__format__','__ge__','__getattribute__','__getitem__','__gt__','__hash__','__iadd__' '_ imul__','__init__','__iter__','__le__','__len__','__lt__','__mul__','__ne__','__new__','__reduce__','__reduce_ex__','__repr__',' _ _ reversed__','__rmul__','_ _ setattr__','__setitem__' '_ _ sizeof__','__str__',' _ _ subclasshook__','append','clear' 'copy','count','extend','index','insert',' pop','remove', 'reverse','sort'] > dir (b) [' _ class__','__delattr__','_ dir__','_ doc__','__eq__','_ format__' '_ ge__',' _ _ getattribute__','_ _ gt__','__hash__','__init__','__iter__','__le__','__length_hint__','_ _ lt__','__ne__','__new__','__next__','__reduce__','__reduce_ex__','__repr__' '_ _ setattr__',' _ _ setstate__','__sizeof__','__str__','__subclasshook__']

You can see that the iterator has the method _ _ next__, and the iterable object has _ _ getitem__

The iterator is consumable. As the pointer moves, it is empty after traversing, but it is not None.

> c = list (b) > c [1,2,3] > d = list (b) > d [] # empty iterator is not equal to None. > if b:... Print (1)... 1 > > if b = = None:... Print (1)...

Use the iterator's built-in methods _ _ next__ and next () to traverse the element

In [73]: e = iter (a) In [74]: next (e) Out [74]: 1 In [75]: e.roomnextframes _ Out [75]: In [76]: e.roomnextframes _ () Out [76]: 2 In [77]: e.roomnextframes _ () Out [77]: 3 In [78]: e.roomnextframes _ ()- -StopIteration Traceback (most recent call last) in ()-> 1 e.roomn extents _ () StopIteration:

When the traversal is complete, an error of StopIteration will be returned.

For...in.... Ergodic iteration

When we use for.... in... for an iterable When traversing, you actually want to call the iter () method to get an iterator, which is assumed to be x, and then call the _ _ next__ () (next ()) method of x to get the value of each time until iterator is empty and returns StopIteration as the standard .forin for the end of the loop. Will automatically handle StopIteration exceptions, thus avoiding throwing exceptions, thus interrupting the program. The flow chart is as follows:

X = [1, 2, 3] for i in x: print (x) after reading the above, have you mastered the role of the generator generator in Python? If you want to learn more skills or want to know more about it, you are welcome to follow the industry information channel, thank you for reading!

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

Internet Technology

Wechat

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

12
Report