1 Generating an iterator
sex = iter ([' Zhao ', ' money ', ' sun ', ' Li ']) #生成迭代器print (Sex) print (sex.__next__ ()) #读取迭代器内容方法 iter.__next__ () sex_1 = Sex._ _next__ () print (sex_1) "<list_iterator object at 0x000001b26572b780> Zhao Qian"
2 Generator yield
Use yield in the function to return the function to an iterator, which is called the generator, the value after yield can be returned, and yield can also receive the passed value
#可以中断生成器函数, the next time you start the Def Cash_money from the Break (amount ): While amount > 0:print (' Take money! ') yield amount-=100def Cost_money (): Print (' It's done! ') ATM = Cash_money (+) print (atm.__next__ ()) print (atm.__next__ ()) Cost_money () print (atm.__next__ ()) "Take the money! 100 Take the money! 100 spent! Take the money! "
Import timedef Customer (name): print ("%s ready to eat buns ... "%name) while True: baozi = yield print ("%s ate%s buns ... "% (name, Baozi)) def conductor (name1): print ("%s started making buns ... "%name1) a = Customer (' a ') #用生成器函数得到一个迭代器 b = Customer (' b ') a.__next__ () #读取迭代器中内容, Prepare to read the contents of yield b.__next__ () for I in range: time.sleep (2) print ("%s times did 2 buns ... "% (i+1)) a.send (1) #向生成器中的yield传入值 b.send (1) conductor (" Zhu ") ' Zhu started making buns ... A ready to eat steamed buns ... b ready to eat steamed buns ... The 1th time did 2 buns ... A ate 1 buns ... B Ate 1 buns ... The 2nd time did 2 buns ... A ate 1 buns ... B Ate 1 buns ... The 3rd time did 2 buns ... A ate 1 buns ... B Ate 1 buns ... The 4th time did 2 buns ... A ate 1 buns ... B Ate 1 buns ... The 5th time did 2 buns ... A ate 1 buns ... B Ate 1 buns ... The 6th time did 2 buns ... A ate 1 buns ... B Ate 1 buns ... The 7th time did 2 buns ... A ate 1 buns ... B Ate 1 buns ... The 8th time did 2 buns ... A ate 1 buns ... B Ate 1 buns ... The 9th time did 2 buns ... A ate 1 buns ... B Ate 1 buns ... The 10th time did 2 buns ... A ate 1 buns ... B Ate 1 buns ... ’‘’
Python learning Essay (vii) iterators