Day4 iterator & amp; generator & amp; Regular Expression, day4 Generator

Source: Internet
Author: User

Day4 iterator & generator & Regular Expression, day4 Generator

1. iterator

An iterator is a way to access collection elements. The iterator object is accessed from the first element of the set until all elements are accessed. The iterator can only move forward, but this is nothing because people seldom step back on the iteration. In addition, the major advantage of the iterator is that it is not required to prepare all elements in the entire iteration process in advance. The iterator calculates an element only when it iterates to an element. Before or after this, the element may not exist or be destroyed. This feature makes it especially suitable for Traversing large or infinite sets, such as n g files.

Specific:

(1). visitors do not need to care about the files in the iterator. They only needUse the next () methodContinue to fetch the next content;

(2). A value in the set cannot be randomly accessed., Which can only be accessed from start to end in sequence;

(3) You cannot accessRollback;

(4). It is easy to generate an iterator for a large set of data loops and saves memory.

Iter () is used to declare the iterator. The example is as follows:

Names = iter (["eric", "aoi", "alex"])
Print (names)
Print (names. _ next __())
Print (names. _ next __())
Print (names. _ next __())

Declare An iterator. When traversing a file, for line in f: is implemented through iteration.

We know that f. read (), f. readline (), f. readlines (), but when we read the file, Python loads the file into the memory and then reads it. The speed will be very slow. We can use the following method to read the file:

With open (filename, "r") as f:

For line in f:

Print (line)

The above Code reads data row by row. In this way, one row and one row are read (next () to read one row and load one row. The implementation method is the iterator, which will speed up reading files, therefore, we can use for line in f: to read large files.

Ii. generator

Definition: When a function is called, an iterator is returned. This function is called a generator. If the function contains the yield syntax, the function becomes a generator.

Def cash_money (amount ):
While amount> 0:
Amount-= 100
Yield 100
Print ("Get the money again ")

Atm = cash_money (500)

The above code is executed, but there is no return value. Why? We executed and called the function. We should print and get the money again, but we didn't print it. Let's take a look at the atm type.

Print (type (atm ))

The running result is as follows:

<Class 'generator'>

The variable atm is a generator and a generator. A function is a generator function, and an iterator is returned. The iterator must use the _ next _ () method for calling:

Def cash_money (amount ):
While amount> 0:
Amount-= 100
Yield 100
Print ("Get the money again ")

Atm = cash_money (500)
Print (type (atm ))
Print (atm. _ next __())
Print (atm. _ next __())
Print ("big health care ")
Print (atm. _ next __())

The running result is as follows:

<Class 'generator'>
100
I got the money again.
100
Big health care
I got the money again.
100

If we write a program to get the money, for example, 50 thousand, the bank needs to review the large amount of money, the review time is 30 minutes, if the general serial program, we need to wait for the bank feedback results, the program can continue to be executed, yield avoids this situation and keeps the program waiting. The program itself executes the following program. Serial is synchronous, while generator is asynchronous.

The generator can continue to execute code from the breakpoint. The generator can save the function interruption status.

Purpose:

The main effect of yield is that it can interrupt the function and save the interrupt status. After the interruption, the code can continue to be executed. After a while, you can call this function again, run the following statement from the last yield statement.

In addition, you can also use yield to implement concurrent operations in the case of a single thread.

Here is an example:

Import time
# Import the time function to wait for the program to run

Def consumer (name ):
# Consumer model
Print ("% s ready to eat steamed stuffed bun! "% Name)
While True:
Baozi = yield
Print ("steamed stuffed bun [% s], it was eaten by [% s! "% (Baozi, name ))

Def producer (name ):
# Two consumers bought steamed buns
C = consumer ("")
C2 = consumer ("B ")
C. _ next __()
C2. _ next __()
Print ("I started preparing for the steamed stuffed bun! ")
For I in range (10 ):
Time. sleep (1)
Print ("made two buns! ")
C. send (I)
C2.send (I)

Producer ("alex ")

 

The import time module defines how long the producer can generate steamed stuffed bun and defines two modules. One is the generator module and the other is the consumption module. The consumer module function tells the producer that a consumer has bought steamed stuffed bun, it also receives the Steamed Stuffed Bun produced by the producer. The producer model receives messages from two consumers and starts to produce steamed stuffed bun. It takes time for the producer to generate steamed stuffed bun, after the steamed stuffed bun is produced, send it to the consumer.

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.