In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-20 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)05/31 Report--
This article is a detailed introduction to "What is the role of iterators and generators in python". The content is detailed, the steps are clear, and the details are properly handled. I hope this article "What is the role of iterators and generators in python" can help you solve your doubts. Let's go deeper and learn new knowledge together with the ideas of Xiaobian.
1. Iterator
An iterator is a way to access elements in a collection, typically to iterate over data. Iterators can only generate data one by one, subscripts cannot be returned. Iterators provide a lazy way to access.
The iterator Iterator implements the__next__and__iter__functions. If only__iter__is implemented, it is an iterable object, such as a list
from collections.abc import Iterable, Iteratorvar_list = [1, 2]print(isinstance(var_list, Iterable)) #Trueprint(isinstance(var_list, Iterator)) #False#var_list iterable, but not iterator
2. Implementation of iterators and iterable objects
from collections.abc import Iterable, Iteratorclass MyIterator(Iterator): #Iterator already implements__iter__method def __init__(self, employee_list):self.employee_list = employee_listself.index = 0 def __next__(self):try: word = self.employee_list[self.index]except IndexError:#for statement can handle StopIteration raise StopIteration self.index += 1 return wordclass Company: #iterable object def __init__(self,employee_list):self.employee_list = employee_listdef __iter__(self):return MyIterator(self.employee_list)if __name__ == '__main__': company = Company(['a', 'b', 'c'])for one_company in company:print(one_company)
In all iteration scenarios of python, the object must be an iterable object, so if an iterator wants to be used in iteration scenarios, it must be an Iterable object; to be an Iterable object, it must comply with the Iterable protocol. By implementing the__iter__function to satisfy the Iterable protocol, it becomes an Iterable object. None of the above functions and tools can be used to iterate over an iterator without implementing the__iter_method, only by manually calling the next() method.
3. Generator
The yield keyword exists in the function, which is the generator function. Generators make deferred evaluation possible.
When python calls a function, the python interpreter creates a stack frame, and all stack frames are allocated on heap memory, which determines that stack frames can exist independently of the caller.
def testGen():yield 1 yield 2if __name__== '__main__':#generator object, generated when python compiles bytecode var_gen = testGen()print(var_gen)# #Generators implement iterative protocols for var_value in var_gen:print(var_value) #1 2#Fibonacci def fib(var_index):if var_index object : var_buf = "" while True:while var_separator in var_buf: var_position = var_buf.index(var_separator)yield var_buf[:var_position] var_buf = var_buf[var_position + len(var_separator) :] var_chunk = var_f.read(4096*10)if not var_chunk:yield var_bufbreak var_buf += var_chunkif __name__ == '__main__':with open('a.txt') as var_f:for var_line in myReadLine(var_f, '{|}'):print(var_line) Read here, this article "What is the role of iterators and generators in python" article has been introduced, want to master the knowledge points of this article also need to be used by yourself to understand, if you want to know more about the relevant content of the article, welcome to 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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.