In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/02 Report--
This article is to share with you about the difference between iterable objects and iterator generators in Python. I think it is very practical, so I share it with you. I hope you can get something after reading this article.
The generator is a special iterator. The generator automatically implements the "iterator protocol" (that is, the _ _ iter__ and next methods). There is no need to implement the two methods manually.
First of all, explain the difference between Iterable and Iterator literally.
Iterable: according to English naming rules, the suffix able means what it can be, so iterable means iterable object.
Iterator: according to English naming rules, the suffix or or er is a pronoun, so iterator means iterator.
There is a relationship between inclusion and inclusion between these two concepts. If an object is an iterator, then the object must be iterable; but conversely, if an object is iterable, then the object is not necessarily an iterator.
Let's take a closer look at iterable objects and iterators:
Iterable:
Given a list or tuple, we can traverse the list or tuple through a for loop, which we call iteration. In python, iteration is done through for. In, which can be used not only on list or tuple, but also on other iterable objects, so how do we know if an object is iterable? The method is to determine the Iterable type of the collections module:
> from collections import Iterable > whether isinstance ('abc', Iterable) # str can be iterated True > isinstance ([1mem2mae3], Iterable) # list whether it can be iterated True > isinstance (123, Iterable) # integer can iterate False
Objects that can act directly on the for loop are collectively referred to as iterable objects. There are two categories, one is the python data types that we usually use, such as list,tuple,dict,set is an iterable object, the string is also an iterable object, but the integer is not an iterable object; the other is generator (a brief explanation is given below)
Iterator:
For the data structure of a list, we have to open up a space for each element in memory, no matter whether you can use it in the future or not, if you want to create a list of 1 million elements, but only a few of them will be used, then this is obviously a waste of memory, so if the list elements can be calculated according to some algorithm Can we keep figuring out the subsequent elements in the process of the cycle? This eliminates the need to create a complete list, saving a lot of space. This loop-while-computing mechanism in python is called generator: generator.
There are many ways to create a generator. The easiest way is to directly change the [] of a list generator to ().
> L = [x * x for x in range (10)] > L [0,1,4,9,16,25,36,49,64,81] > > g = (x * x for x in range (10)) > > g
You can see that the list created outputs all the elements, while the generator just generates an object. If you use the elements in it, you can call the next of the generator.
> next (g) 0 > next (g) 1 > next (g) 4 > next (g) 9 > next (g) 16 > next (g) 25 > next (g) 36 > next (g) 49 > next (g) 64 > > next (g) 81 > next (g) Traceback (most recent call last): File ", line 1, in StopIteration
The next method is too laborious, or it can be done through the for loop
> g = (x * x for x in range (10)) > for n in GRV. Print (n)... 0149162536496481
The above is to pave the way for the iterator to be discussed later, and here are the key points
Not only can the generator act on the for loop, it can also be called repeatedly by the next () function and return the next value until finally a StopIteration error is thrown indicating that the next value cannot be returned.
An object that can be called by the next () function and constantly returns the next value is called an iterator: Iterator.
You can use isinstance () to determine whether an object is an Iterator object:
> from collections import Iterator > isinstance ((x for x in range (10)), Iterator) True > isinstance ([], Iterator) False > isinstance ({}, Iterator) False > isinstance ('abc', Iterator) False
Generators are all Iterator objects, but list, dict, and str are Iterable, but not Iterator.
To change an Iterable such as list, dict, str into Iterator, you can use the iter () function:
> isinstance (iter ([]), Iterator) True > isinstance (iter ('abc'), Iterator) True
Why are list, dict, str and other data types not Iterator?
Because the Iterator object of python represents a data stream, the Iterator object can be called by the next () function and continue to return the next data until a StopIteration error is thrown when there is no data. We can think of this data stream as an ordered sequence, but we can't advance to the length of the sequence, we can only use the next () function to calculate the next data on demand, so the calculation of Iterator is lazy, and it will only be calculated when we need to return the next data.
Iterator can even represent an infinite data stream, such as all natural numbers, which can never be stored in a list.
Summary:
All objects that can act on for loops are of type Iterable and can be iterated.
Any object that can be used as a next () function is of type Iterator, which represents a sequence of lazy calculations.
Collection data types such as list,dict,str are Iterable but not Iterator, but an Iterator object can be obtained through the iter () function.
The creation of generator: 1. Use the generator derivation of the for loop. two。 Call the generator function with the yield statement.
Similarities and differences between iterators and birth instruments
one。 Iterator
The iterator object of the list is obtained through the iter () method, and then the elements in the list can be accessed through the next () method. When there are no accessible elements in the container, the next () method throws a StopIteration abort iterator.
two。 Generator
If the list elements can be calculated according to some algorithm, can we continue to calculate the subsequent elements in the process of the loop? This eliminates the need to create a complete list, saving a lot of space. In Python, this mechanism of calculating while looping is called Generator.
This is the difference between iterable objects and iterator generators in Python. The editor believes that there are some knowledge points that we may see or use in our daily work. I hope you can learn more from this article. For more details, please 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.
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.