1. iterables
Have the ability to be iterative, that is enumerable, in the middle of a python can go to access the elements of some of the objects one by one through the for-in, such as tuples tuple, list list, string string, file object file and so on.
2. iterator
An access element may be an iterative object, enumerator another way. In the middle is a python to a built-in function ITER () passing an iterator object as a parameter, that object is returned iterator () method to access by the next one by the iterator.
3. Generator
Generator is essentially a function of the return element individually, is essentially a function.
The biggest advantage is that it is "lazy loading", that is to deal with a long sequence of questions, more to save storage space. I.e., each time the generator is stored in memory only a value, such as printing a series Feibolaqie: original approach can be as follows
def fab(max):
n, a, b = 0, 0, 1
L = []
while n < max:
L.append(b)
a, b = b, a + b
n = n + 1
return L
The biggest problem is to do so all of the elements which are stored in the L, the memory is occupied, the use of the generator as shown below
def fab(max):
n, a, b = 0, 0, 1
while n < max:
yield b # each iteration of a time when it is loaded element, and replace that element before the fall, thus greatly save memory. And the program will stop when met at a yield statement, which is the principle behind the use of yield blocking multithreaded programming an inspiration, (python coroutine program will be mentioned later)
a, b = b, a + b
n = n + 1
In fact, the generator will look like, write a simple return some of that time, as follows:
def generator():
for i in range(5):
yield i
def generator_1():
yield 1
yield 2
yield 3
yield 4
yield 5
4. yield from
yield from generator. ActuallyFurther returns a generator
def generator1():
item = range(10)
for i in item:
yield i
def generator2():
yield ‘a‘
yield ‘b‘
yield ‘c‘
yield from generator1 () #yield from the iterable is essentially equal for item in iterable: yield item abbreviated version of
yield from [11,22,33,44]
yield from (12,23,34)
yield from range(3)
for i in generator2() :
print(i)
From the above code can be read,yield from There can be followed by the expression "Generator list of tuples, etc.Iterables andrange()Function produces a sequence "
The results of running the above code is:
a
b
c
0
1
2
3
4
5
6
7
8
9
11
22
33
44
12
23
34
0
1
2
Original Address: https: //www.cnblogs.com/zhuifeng-mayi/p/9248641.html