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 principle of Python iterator and how to use it

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article mainly introduces the principle of Python iterator is what and how to use the relevant knowledge, the content is detailed and easy to understand, simple and fast operation, with a certain reference value, I believe that after reading this Python iterator principle is what and how to use the article will have a harvest, let's take a look at it.

What is an iterator?

An object that can be called by a next pointer and constantly returns the next value is called an iterator. Represented as Iterator, the iterator is an object type data.

Concept

Iterator refers to the tool of iterative value, iteration is a repetitive process, each iteration continues based on the previous result, simple repetition is not iteration.

Features

The iterator does not rely on the index, but iterates over all the data through the next pointer, taking only one value at a time, saving a lot of space.

Inert sequence

Lazy sequence means that instead of putting all the data in the sequence at once, range objects and iterators can produce lazy sequences.

Check iterable objects

The for loop is used to traverse iterable objects. Roughly speaking, the elements that can be traversed by the for loop are iterable objects. The reason why the for loop can traverse all iteratable data is that the underlying iterator is called to fetch the data through pointers in the next method. So the difference between a normal non-iterator iterable object and an iterator is that one cannot be called directly using next, and the other can be called by a next pointer.

Again, an iterable object is not necessarily an iterator, an iterator must be an iterable object.

Use the dir () function to view all the object members in a data, and if you include the _ _ iter__ method, it is an iterable object. In other words, the function of the _ _ iter__ method is to return an iterable object.

# define a list The list is an iterable object lst = [1, 2, 3, 4, 5] # get all members of the list res_lst = dir (lst) print (res_lst)''['_ add__','_ class__','_ contains__','_ delattr__','_ delitem__','_ dir__','_ doc__','_ eq__','_ format__' '_ _ ge__',' _ _ getattribute__','_ _ getitem__','_ _ gt__','_ _ hash__','_ _ iadd__','_ _ imul__','_ _ init__','_ _ init_subclass__','_ _ 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']''# check to see if there is a _ _ iter__ method res ='_ _ iter__' in res_lstprint (res) # True# has a _ _ iter__ method It means that it is indeed an iterable object definition iterator.

The representation of the iterator is iterator.

Use the iter function

Use the iter function to convert a normal iterable object into an iterator.

Lst = [1,2,3] print (type (lst)) # it = iter (lst) print (type (it)) # use the _ _ iter__ method

Use the _ _ iter__ built-in method to convert iterable objects into iterators.

Lst = [1,2,3] print (type (lst)) # it = lst.__iter__ () print (type (it)) # determine the iterator to check the built-in method

There is a _ _ iter__ method that indicates that it is an iterable object. The existence of the _ _ next__ method indicates that it is an iterator because the iterator can use the next pointer to get the element.

Both _ _ iter__ and _ _ next__ exist in the iterator.

The production card is an iterative object.

# list lst = list () # iterator lst_it = iter (lst) # all members of the iterator res_lst = dir (lst_it) # determine if'_ iter__' in res_lst: print ('lst_it is an iterable object') if'_ next__' in res_lst: print ('lst_it is an iterator') 'result: lst_it Is an iterable object lst_it is an iterator''using the collections module

Importing the Iterator and Iterable types in the collections module can determine whether they are iterable objects or iterators. Iterator is iterator type data. Iterable is iterable object type data. You can determine the type of data by using the imported data type combined with the isinstance function.

Lst = list () lst_it = iter (lst) # determine whether it is an iterator res = isinstance (lst_it, Iterator) print (res) # True# determine whether it is an iterable object res = isinstance (lst_it, Iterable) print (res) # True call iterator

Several methods of calling iterator

Use the next function or the _ _ next__ built-in method to get the data one by one, over and over again

Use for to loop through it

Use the while loop with the next function or the _ _ next__ built-in method

Forcibly converted to other data types

Using next methods and functions

The calling iterator uses the next function to extract the contents. Next is one-way irreversible when calling the data in the iterator, which is a process of going black. If the call exceeds the number of elements in the iterator, it will report an error StopIteration, which means to stop the iteration.

# because lst does not have data, it cannot be fetched lst = list () lst_it = iter (lst) res = next (lst_it) # StopIterationprint (res)

Take out the data in the iterator, and if all the data is taken out, you have to reset the iterator to get it out again.

Lst = [1,2,3] lst_it = iter (lst) # iterator only fetches one data at a time print (next (lst_it)) # 1print (next (lst_it)) # 2print (next (lst_it)) # "exceeds the number of elements in the iterator, it will report an error print (next (lst_it)) # StopIteration# if you want to retrieve the data, reset the iterator To redefine a side iterator is to reset the iterator lst_it = iter (lst) # fetch the data again, and use the _ _ next__ method print (lst_it.__iter__ ()) # 1print (lst_it.__iter__ ()) # 2print (lst_it.__iter__ ()) # 3 to introduce the article "what is the principle of the Python iterator and how to use it". Thank you for reading! I believe you all have a certain understanding of "what is the principle of Python iterator and how to use it". If you want to learn more, you are welcome to follow 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