Python Learning Notes Generator and iterator, built-in functions

Source: Internet
Author: User
Tags generator iterable

    • Generator
    • Iterators
    • Built-in functions
    • Homework
First, generator

1.1. List Generator

Problem Introduction: See List [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], I ask you to add 1 to each value in the table

Programme one:

A = [1,3,4,6,7,7,8,9,11]for index,i in Enumerate (a):    A[index] +=1print (a) original value modified

Scenario Two:

>>> a[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]>>> a = map (lambda x:x+1, a) >>> A<map object at 0X101D2C 630>>>> for I in A:print (i) ... 357911

Scenario Three: List Builder

>>> a = [i+1 for i in range]]>>> a[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

1.2, why should there be generators?

With list generation, we can create a list directly. However, with memory limitations, the list capacity is certainly limited. Also, creating a list of 1 million elements takes up a lot of storage space, and if we just need to access the first few elements, the vast majority of the space behind it is wasted.

So, if the list element can be calculated according to an algorithm, can we continue to calculate the subsequent elements in the process of the loop? This eliminates the need to create a complete list, which saves a lot of space. In Python, this side loop computes the mechanism, called the generator: Generator.

1.3. How the generator is created

Method one, directly to the list generator "" into ():

>>> L = [x * x for x in range]]>>> l[0, 1, 4, 9, N, F, $, $, 81]>>> g = (x * x for X In range (+) >>> G<generator object <genexpr> at 0x1022ef630>

It can be noted that G is no longer a list generator, but a generator Object!!!!

Method two, in addition to rewriting the List Builder to construct the generator object, can also be implemented with a function:

Just need to put Print-->yield

def fib (max):    N, a, b = 0, 0, 1 while    n < max:        print (b)        A, B = B, a + b        n = n + 1    return ' done ' ##################################################>>> fib (Ten) 11235813213455done####################### ############################ #def fib (max):    n,a,b = 0,0,1 while    n < max:        #print (b)        yield  b A,        b = b,a+b        n + = 1    return ' done ' ###################################################>>> f = FIB (6) >>> F<generator object fib at 0x104feaaa0>

As you can see, the function implements the same function, that is, after Print-->yield, the FIB (6) becomes a generator object instead of a normal function.

1.4, how to use Gengrator?

If you want to print out one, you can next() get the next return value for generator by using a function:

g = (x * x for x in range) >>> next (g) 0>>> next (g) 1>>> next (g) 4>>> next (g) 9>> > Next (g) 16>>> next (g) 25>>> next (g)

Generator saves the algorithm, each time it is called next(g) , computes g the value of the next element until it is calculated to the last element, no more elements are thrown when the StopIteration error

After we create a generator, we basically never call next() it, but iterate over it through the for loop and don't need to be concerned about StopIteration the error.

>>> g = (x * x for x in range) >>> for n in G: ...     Print (n) ... 0149162536496481

1.5. Summary + Comprehension Difficulties

def fib (max):    n,a,b = 0,0,1 while    n < max:        #print (b)        yield  B, a        = b,a+b        n + = 1    Return ' done ' data = fib (data) print (data.__next__ ()) print (data.__next__ ()) print ("Do something Else") print (Data.__next __ ()) print (data.__next__ ()) print (data.__next__ ()) print (data.__next__ ()) print (data.__next__ ()) ################# ##################### #输出 <generator Object fib at 0x101be02b0>11 do something else 235813

The hardest thing to understand is that generator is not the same as the execution of a function. The function is executed sequentially, the statement is encountered return or the last line of the function is returned. The function that becomes generator, executes at each invocation next() , encounters a yield statement return, and executes again from the last yield statement returned . on top The fib example, which we constantly call during the loop yield , is constantly interrupted

Second, iterators
    • Any object that can be used for for the loop is a Iterable type;

      All objects that can be used for next() functions are Iterator types, which represent a sequence of lazy computations (generators must be iterators);

      Collection data types such as list , dict ,, and str so on are Iterable not Iterator , however, you can iter() get an object from a function Iterator .

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

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

You can use to isinstance() determine whether an object is an Iterator object:

>>> from Collections Import iterator>>> isinstance ((x to X in range), Iterator) true>>> are Instance ([], Iterator) false>>> isinstance ({}, Iterator) false>>> isinstance (' abc ', 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
Three, built-in function four, work

Job Requirements:

Analog implementation of an ATM + shopping mall Program

    1. Quota 15000 or Custom
    2. Realize shopping mall, buy things to add shopping cart, call credit card interface Checkout
    3. Can withdraw, handling fee 5%
    4. 22nd monthly Billing, 10th monthly repayment date, overdue, according to the total amount owed 5 daily interest
    5. Multi-Account Login support
    6. Support transfer between accounts
    7. Record monthly daily consumption flow
    8. Provide repayment interface
    9. ATM Record Operation Log
    10. Provide management interface, including adding account, user quota, freezing account, etc...
    11. Decorator for user authentication

Python Learning Notes Generator and iterator, built-in functions

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.