In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article is about how Python generators and iterators are used. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.
1. Generator
Now you can create a list directly through the generator, but due to memory constraints, the capacity of the list must be limited. If we need a list of hundreds of elements, but only access a few of them each time, then it is a waste of memory space if the remaining elements are not used.
At this point, the Generator plays a role, generating new data according to a certain algorithm until a specified condition is met.
The generation can be obtained in the following ways:
The generator is obtained by list generation, and the sample code is as follows:
G = (x for x in range (10)) # change the [] of the list generation column to () # print its type print (type (g)) # # call its element print (g.roomroomnextcolumns _ ()) # 0print (g.roomroomnextcolumns _ ()) # 1print (g.roomroomnextcolumns _ ()) # 2print (g.roomnextcolumns _ ()) # 3print (g.roomnextcolumns _ () ) # calling print (next (g)) # 5print (next (g)) # 6print (next (g)) # 7print (next (g)) # 8print (next (g)) # calling print (next (g)) using next () # error StopIteration will be reported when the data is not available
How many calls are needed, and those that are not called will not be generated, so they will not take up memory space. You can use a loop structure to call as needed.
G = (x for x in range (10)) # change the [] of the list generation column to () skip = True # judgment condition count = 0 # number of calls while skip: count + = 1 # loop + 1 print (next (g)) if count > 9: break # jump out of the loop
Use the function to complete a generator with the help of the yield keyword to generate the first 20 numbers of the Fibonacci series. The sample code is as follows:
Def fun (length): a, b = 0,1 for _ in range (length): a, b = b, a + b yield afib = fun (20) print (type (fib)) # # print type count = 0while count < 20: # 1 1 23 58 13 21 55 89 144 233 377 687 1597 2584 4181 6765 print (next (fib), "end=") count + = 1
The process is as follows:
During execution, execution will be paused when it encounters the yield keyword, and the next call will continue execution from where it was last paused. Because it is a circular statement, all will jump directly to the for statement.
If you are calling yield and you need to pass it a value, you will use the .send () method.
The sample code is as follows:
Def fun (num): n = 0 for i in range (num + 1): n + = I ret = yield n print (f "this is the {I + 1} from + to {ret}") g = fun (3) print (g.send (None)) print (g.send ('3') print (g.send ('3')) print (g.send ('3'))''--output result-
The addition of send can make the generator more flexible, but it is important to note that when the generator's send () method is called for the first time, the argument must be None, otherwise an exception will be thrown. Of course, you can also call the next () method once before calling the send () method, so that the generator enters the yield expression first.
2. Iterators and iterable generators
Iterable objects include generators, tuples, lists, collections, dictionaries, strings, etc.
The Iterable function of collections is combined with isinstance (object, classinfo) to judge that an object is not an iterative object.
Iteration is a way to access collection elements. An iterator is an object that remembers the location of the traversal. The iterator object is accessed from the first element of the collection until all elements have been accessed. Iterators can only move forward, not backward. A very generator is also an iterator.
An object that can be called by the next () function and constantly returns the next value is called an iterator: Iterator, and you can use isinstance () to determine whether an object is an Iterator object:
Note: it is not necessarily the generator that can be iterated, but the generator must be iterated.
You can use the iter () function to change tuples, lists, collections, dictionaries, strings and other Iterable into Iterator.
The difference between Iterable and Iterator**** is that Iterable can be used as a general term for for loop objects; while Iterator objects need to be called by the next () function to continue to return the next data, until no data is thrown StopIteration error, and until then will not know its length, so the calculation of Iterator is lazy, only the next () function will return the result, Iterator can even represent an infinite data flow, such as all natural numbers.
From collections.abc import Iterable, Iteratora = [1,2,3] b = {1,2,3} c = (1,2) 3) d = "123f = (x for x in range (5)) # print data type print (type (a)) # print (type (b)) # print (type (c)) # print (type (d)) # print (type (e)) # print (type (f)) # print ("-"* 20) # print is an iterable object print (isinstance (a, Iterable)) # Trueprint (isinstance (b, Iterable)) # Trueprint (isinstance (c) Iterable) # Trueprint (isinstance (d, Iterable)) # Trueprint (isinstance (e, Iterable)) # Falseprint (isinstance (f, Iterable)) # Trueprint ("-" * 20) # all but strings are iterable objects # print is an iterator print (isinstance (a, Iterator)) # Falseprint (isinstance (b, Iterator)) # Falseprint (isinstance (c, Iterator)) # Falseprint (isinstance (d, Iterator)) # Falseprint (isinstance (f)) Iterator)) # True# only f (generator) is an iterator print ("-" * 20) # convert iteratively into an iterator print (isinstance (iter (a), Iterator) # Trueprint (isinstance (iter (b), Iterator)) # Trueprint (isinstance (iter (c), Iterator)) # Trueprint (isinstance (iter (d), Iterator)) # True thanks for your reading! This is the end of this article on "how to use Python generators and iterators". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, you can share it for more people to see!
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.