The Builder (Generator) summary in Python

Source: Internet
Author: User
Tags for in range iterable

1. Two ways to implement generator

The generator in Python holds the algorithm and calculates the value when it really needs to be computed. It is an inert calculation (lazy evaluation).

There are two ways to create a generator.

The first method: Changing a list-generated formula [] () to create a generator:

 for  in range () >>> 1, 4, 9, +, (+), +, +, Bayi]for in Range (+)   # Note When you change [] to (), instead of generating a tuple, you generate a generator>>> g<generator Object <genexpr> at 0x1022ef630>

The second way: by using the yield keyword in a function, the function becomes a generator.

After the yield in the function, the execution to yield will stop, when the need to further down the calculation will be counted. So the generator function does not matter if there is an infinite loop, it needs to calculate how much will be counted, do not need to calculate.

def fib ():
A, b = 0, 1
While True:
Yield a
A, B = B, A + b


f = fib ()
Print F, Next (f), Next (f), Next (f)
# <generator Object fib at 0x7f89769d1fa0> 0 1 1

As the above example, the first output F, it is a generator, and then every time next, it executes to yield a.

Of course, in fact, rarely use next (), we directly with the For loop can traverse a generator, in fact, the internal implementation of the For loop is to call next ().

Generators can avoid unnecessary computations, improve performance, and save space for an infinite loop (infinitely large) data structure.

2.the concept of an iterative object (iterable) and an iterator (Iterator)

An object that can directly act on for a loop is called an iterative object: Iterable .

Includes collection data types (,,,, list tuple , and dict set str so on) and generators (generator).

You can use to isinstance() determine whether an object is an Iterable object.

 from Import iterable>>> isinstance ([], iterable) True>>> isinstance ({}, iterable) True>>> isinstance ('abc', iterable) True for  in range (), iterable) True>>> isinstance (iterable) False

迭代器:Iterator。

It represents a data stream where the iterator object can be called by a next() function and continually returns to the next data until there is no data to throw an StopIteration error. You can think of this data stream as an ordered sequence, but we can't know the length of the sequence in advance, only by continuously using the next() function to calculate the next data on demand, so Iterator the calculation is lazy, and it will only be calculated when the next data needs to be returned. IteratorIt can even represent an infinitely large stream of data, such as the whole natural number. Using list is never possible to store all natural numbers.

The generator (generator) is an Iterator object, but,, list dict str Although Yes Iterable , it is not Iterator .

Turn list , dict and str wait for the Iterable Iterator function to be used iter() :

>>> Isinstance (ITER ([]), Iterator) True>>> isinstance (iter ('ABC ' ), Iterator) True

The Python for loop is essentially implemented by calling next() functions, such as:

 for inch [1, 2, 3, 4, 5]:     Pass

is actually exactly equivalent to:

# first Get Iterator object:it = iter ([1, 2, 3, 4, 5])#  loop: while True:     Try :         # get the next value:        x = Next (it)    except  stopiteration:        #  Exit loop break when encountering stopiteration        

3.itertools Module

Python's built-in module, Itertools, provides functions for manipulating iterative objects, which are convenient and practical. To give an example:

I Slice (iterable, [Start,] stop [, step]):

Creates an iterator that generates an item in a way similar to the slice return value: iterable[start:stop:step], skips the previous start item, iterates over the stop at the specified stop, and step specifies the stride used to skip the item. Unlike slices, negative values are not used for any start,stop and step, and if Start is omitted, the iteration will start at 0 and if step is omitted, the stride will take 1.

 from Import Islice def fib ():     = 0, 1 while      True:        yield  a        = B, A += fib ()  print list (Islice (f, 10))
# [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

The Builder (Generator) summary in Python

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.