Python Learning 2: Generators, iterators, adorners __python

Source: Internet
Author: User
Tags generator iterable wrapper in python

1, generator
With a list generation, we can create a list directly. However, the list capacity is certainly limited by the memory limit. Also, create a containing 1 million
The list of elements, not only takes up a lot of storage space, if we only need to access the first few elements, then most of the space occupied by the back of the waves
Fee.

So if the list element can be calculated according to some algorithm, then whether we can continue to calculate the subsequent elements in the process of the loop. So you don't have to create
Build a complete list, thus saving a lot of space. In Python, this loop-side computing mechanism is called the generator: Generator.

There are a number of ways to create a generator. The first method is simple, as long as you change a list-generated [] to (), you create a generator:


L = [x * x for x in range (10)]
g = (x * x for x in range (10))

The difference between creating L and G is only the outermost [] and (), L is a list, and G is a generator.

We can print out every element of the list directly, but how do we print out every element of the generator.

If you want to print one one out, you can get the next return value of generator through the next () function
When there are no more elements, throw the stopiteration error.

def fib (max):
	N, a, b = 0, 0, 1 while
	n < max:
		print (b)
A, B = B, a + b
n = n + 1 return
' done '


def fib (max):
	n,a,b = 0,0,1 while

n < max:
	yield b
a,b = b,a+b

n + + 1 return

' done

'

Iterators
We already know that there are several types of data that can be directly applied to the For loop:

A class is a set of data types, such as list, tuple, dict, set, str, etc.
The class is generator, including generators and generator function with yield.
These objects, which can directly affect the for loop, are called iterated objects: Iterable.
You can use Isinstance () to determine whether an object is a Iterable object:
The generator can be used not only for the For loop, but also for the next () function to call and return the following value

* An object that can be called by the next () function and continually return the next value is called an iterator: iterator.

From collections Import iterator
Isinstance ((x for X in range ()), iterator)

Generators are iterator objects, but list, dict, str, although iterable, are not iterator.
The ITER () function can be used to turn the iterable of list, dict, str, etc. into iterator:

You may ask why the data types such as list, dict, str are not iterator.

This is because the Python iterator object represents a stream of data, and the iterator object can be called by Next () function and returned to the next data continuously until no
Throws a stopiteration error when there is data. This data stream can be thought of as an ordered sequence, but we can't know the length of the sequence in advance, we can only keep
By using the next () function to compute the next data on demand, the iterator calculation is inert and will only be evaluated if the next data needs to be returned.

Iterator can even represent an infinitely large stream of data, such as all natural numbers. and using list is never possible to store all the natural numbers.

Summary

All objects that can be used for a for loop are iterable types;

Objects that can be used for the next () function are iterator types, which represent a sequence of lazy computations;

Collection data types such as list, dict, str, etc. are iterable but not iterator, but you can get a iterator object from the ITER () function.

The python for loop is essentially implemented by continually invoking the next () function


Decorative Device

A function is a higher order function if one of the following conditions is met
1, a function as a parameter passed into another function
2, the return value of the function contains n functions, n>0

inline function + High-order function + closure = "Adorner"


Example one:

Import Time
def decorator (func):
	def wrapper (*args,**kwargs):
		start=time.time ()
		func (*args,** Kwargs)
		stop=time.time ()
		print ' Run time was%s '% (stop-start)
		print timeout return
wrapper

@ Decorator
def Test (list_test): For
	i in List_test:
		time.sleep (0.1)
		print '-' *20,i


# Decorator (test) (range) 
test (range)

two:
import time
def timer (timeout=0):
def Decorator (func):
def wrapper (*args,**kwargs):
start=time.time ()
func (*args,**kwargs)
stop= Time.time ()
print ' Run time was%s '% (stop-start)
print timeout return
wrapper return
decorator

@timer (2)
def Test (list_test): For
i in List_test:
time.sleep (0.1)
print '-' *20,i

Test (range (10))




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.