Python Learning Note-day4

Source: Internet
Author: User

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 build an iterator:

A = ITER (['John','Teddy','Tony' ) ,'nina'])print(a)


Access list content:

A = ITER (['John','Teddy','Tony','Nina'])Print(a)Print(A.__next__())Print(A.__next__())Print(A.__next__())Print(A.__next__())



Execution Result:

<list_iterator object at 0x006ca2b0>Johnteddytonynina

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

defCash_money (amount): whileAmount >0:amount-=100yield100Print("We 're taking the money again.") ATM=cash_money (500)Print(ATM.__next__())Print(ATM.__next__())Print(ATM.__next__())Print("Interrupts")Print(ATM.__next__())

Role:

The main effect of this yield is that the function can be interrupted, and save the interrupt state, after the interruption, the code can continue to execute, after a period of time can also recall the function, from the last yield of the next sentence to start execution.

Asynchronous applications

Yield can also be implemented in single-threaded cases to achieve the effect of concurrent operations.

Import TimedefConsumer (name):Print("%s ready to eat buns!"%name) whileTrue:baozi=yield       Print("Bun [%s] came, eaten by [%s]!"%(baozi,name))defproducer (name): C= Consumer ('A') C2= Consumer ('B') c.__next__() c2.__next__()    Print("Lao Tzu began to prepare steamed buns!")     forIinchRange (10): Time.sleep (1)        Print("made 2 buns!") c.send (i) c2.send (i) Producer ('Candy')

adorners Because a function is also an object, and a function object can be assigned to a variable, the function can also be called through a variable.

def welcome ():      ... Print ('Welcome to visit my home page! ' )... >>> f = welcome>>> F () Welcome to visit my home page!

defLogin (func):defIner (*args,**Kwargs):Print("passed user verification ....") func (*args,**kwargs)#func = TV    returnInerdefHome (name):Print("Welcome [%s] to home page"%name)#def TV (name):@login#= TV Login (TV) perform the function "login"defTV (name):Print("Welcome [%s] to Tv page"%name)defMovie (name,pwd="123"):    Print("Welcome [%s] to movie page"%name)#TV = login (TV)Tv"Alex") Movie ("Mikey", pwd="123")






Because a function is also an object, and a function object can be assigned to a variable, the function can also be called through a variable.

Python Learning Note-day4

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.