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

How to write the generator and iterator code of Python3

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

Share

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

This article mainly explains "Python3 generator and iterator code how to write," interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Let's let Xiaobian take you to learn "how to write Python3 generator and iterator code"!

1. Generator #A mechanism for calculating while looping is called generator: generator;#Create generator method: # 1. Change [] of a list generator formula to ()numsList = [num * num for num in range(10)]print ("numsList: ",numsList)numsGenerator =(num * num for num in range(10))print ("generator generates numsGenerator: ",numsGenerator)#Use the next() function to get the next return value of generator print ("print numsGenerator first element: ",next(numsGenerator))print ("Print second element of numsGenerator: ",next(numsGenerator))print("---------------------------------")#Print generator element using for loop print("Print elements in generator using loop! ")for num in numsGenerator: print(num,end = " ")print("\n")print("----------------------------------")#Fibonacci (num): Any number except the first and second numbers can be added to # 1,1,2,3,5,8,13,21,34def fibonacci(num): n, a, b = 0, 0, 1 while n < num: print(b,end = " ") a, b = b, a + b n = n + 1 return "Done"print("Fibonacci's first 10 terms are: ")fibonacci(10)print("\n")print("----------------------------------------")#2. Change the fibonacci() function to the generator function def fibonacci(num): n, a, b = 0, 0, 1 while n < num: yield b a, b = b, a + b n = n + 1 return "Done"# Tips: #1. A function is a generator function if its definition contains the yield keyword;#2. Calling a generator function returns a generator;fib = fibonacci(10)print("fib's value: ",fib)

#Result output:

NumsList is generated by list generation formula: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

Generator generates numsGenerator:

Print numsGenerator first element: 0

Print numsGenerator second element: 1

--------------------------------------------------------

Print elements in the generator using a loop!

4 9 16 25 36 49 64 81

--------------------------------------------------------

The first 10 Fibonacci items are:

1 1 2 3 5 8 13 21 34 55

--------------------------------------------------------

Value of fib:

#Execution flow of ordinary function and generator function: # 1. Ordinary function: executed sequentially, returning when encountering return statement or last line of function statement;#2. Generator function: executed every time next() is called, returning when encountering yield statement;# 3. Executed again from yield statement returned last time;#Example: Define a generator function, returning "Willard", 18,"Engineer"def willardInfo() in turn: print("STEP1") yield "Willard" print("--------") print("STEP2") yield 18 print("--------") print("STEP3") yield "Engineer"#Call willardInfo() this generator function, sir into a generator object #and then use the next() function to continuously obtain the next return value, that is, directly print willardInfoObject = willardInfo()for willard in willardInfoObject: print(willard)

#Result output:

STEP1

Willard

--------

STEP2

18

--------

STEP3

Engineer

2. Iterator #Data types that can be directly used in for loops: # 1.list, tuple, dict, set, str, etc.;# 2.generator, including: generator and generator function with yield;# 3. Objects that can be directly used in for loops are called iterable objects: Iterable;# 4. Use isinstance() to determine whether an object is an Iterable object;from collections.abc import Iterableprint("Determine whether a list is an Iterable object! ",isinstance([],Iterable))print(" Determine whether dict is an iterable object! ",isinstance({},Iterable))print(" Determine whether str is an iterable object! ",isinstance("Willard",Iterable))print(" Determine whether the generative expression is an iterable object! ",isinstance((num for num in range(10)),Iterable))print(" Determine whether number is an iterable object! ",isinstance(99,Iterable))

#Result output:

Determine if list is iterable! True

Determine whether dict is an iterable object! True

Determine if str is an iterable object! True

Determine whether the generative expression is an iterable object! True

Determine if number is an iterable object! False

#Objects that can be called by the next() function and keep returning the next value are called iterators: Iterator#Use isinstance() to determine whether an object is an Iterator object;from collections.abc import Iteratorprint("Determine whether a generator is an iterator! ",isinstance((num for num in range(10)),Iterator))print(" Determine if list is an iterator! ",isinstance([],Iterator))print(" Determine whether dict is an iterator! ",isinstance({},Iterator))print(" Determine if str is an iterator! ",isinstance ("Willard",Iterator))print ("---------------------------------------")# Tips:# 1. Generators are Iterator objects, but list, dict, str are Iterable but not Iterator;#2. Iterator objects represent data streams, Iterator objects can be called by the next() function and keep returning the next data,#StopIteration errors are thrown until there is no data; This data stream can be regarded as an ordered sequence,#but you can't know the length of the sequence in advance, you can only calculate the next data on demand through the next() function,# Iterator's calculation is lazy, only when you need to return the next data;# 3. Use iter() function to change list, dict, str into Iterator;print("Use iter() function to change list, dict, str into Iterator. ")print(" determine if list is an iterator! ",isinstance(iter([]),Iterator))print(" Determine whether dict is an iterator! ",isinstance(iter({}),Iterator))print(" Determine if str is an iterator! ",isinstance(iter("Willard"),Iterator))

#Result output:

Determine if the generator is an iterator! True

Determine if list is an iterator! False

Determine whether dict is an iterator! False

Determine if str is an iterator! False

----------------------------------------------------------

Use iter() to change list, dict, str to Iterator.

Determine if list is an iterator! True

Determine whether dict is an iterator! True

Determine if str is an iterator! True

At this point, I believe everyone has a deeper understanding of "how to write Python3 generator and iterator code," so let's actually operate it! Here is the website, more related content can enter the relevant channels for inquiry, pay attention to us, continue to learn!

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