Definitions and cases for python--iterators and generators

Source: Internet
Author: User
Tags generator generator

Iterators

Iterators are a way to access the elements of a collection. The iterator object is accessed from the first element of the collection until all of the elements have been accessed and finished. Iterators can only move forward without going backwards, but that's fine, because people seldom retreat in the middle of an iteration. In addition, one of the great advantages of iterators is that they do not require that all elements in the entire iteration be prepared in advance. An iterator computes an element only when it iterates over it, and before or after that, the element may not exist or be destroyed. This feature makes it ideal for traversing large or infinite collections, such as several G files

Characteristics:

    1. The visitor does not need to care about the structure inside the iterator, but simply continues to fetch the next content through the next () method
    2. A value in the collection cannot be accessed randomly, and can only be accessed from beginning to end
    3. You can't go back halfway through the interview.
    4. Facilitates recycling of large data sets, saving memory

To generate an iterator:

 #  !/usr/bin/env python  #  -*-coding:utf-8-*- #   Author:huanglinsheng  hls  = iter ([ 1,2,3,4,5])  print  (hls.__next__   ())  print  (HLS. __next__   ())  print  (Hls. __next__   ())  print  (Hls.__next__   ())  print  (Hls. __next__  ()) 

Generator generator

Definition: When a function call returns an iterator, the function is called the Generator (generator), and if the function contains the yield syntax, the function becomes the generator

Code:

#!/usr/bin/env python#-*-coding:utf-8-*-#Author:huanglinshengdefFIB (max):#TenN, a, b = 0, 0, 1 whileN <Max:#print (b)        yieldb A, b= B, A +B N= n + 1return '---done---'F= FIB (10) forIinchF:Print(i)

Code after adding new content:

#!/usr/bin/env python#-*-coding:utf-8-*-#Author:huanglinshengdefFIB (max):#TenN, a, b = 0, 0, 1 whileN <Max:#print (b)        yieldb A, b= B, A +B N= n + 1return '---done---'g= FIB (10) whileTrue:Try: x=Next (g)Print('g:', X)exceptstopiteration as E:Print('Generator return value:', E.value) Break

Generator parallel case (game recharge):

#!/usr/bin/env python#-*-coding:utf-8-*-#Author:huanglinshengImport TimedefDaozhang (name):Print(""%s" ready to recharge the game! "%name) whileTrue:money=yield        Print("[%s] has already been recharged [%s] Yuan! Really rich. "%(Name,money))defChongzhi (name): Dz1= Daozhang ("Hucong") dz2= Daozhang ("Huanglinsheng") dz1.__next__() dz2.__next__()    Print(""%s" to help recharge"%name) forIinch(50,100,200,300): Time.sleep (1)        Print("===== start recharging ======") dz1.send (i) dz2.send (i) Chongzhi ("Huanghongtao")

Operation Result:

Definitions and cases of python--iterators and generators

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.