Python-Generator

Generator

yield():

in ordinary function

Coroutine(协同程序):

可以运行的独立函数的调用,函数可以暂停或者挂起,并在需要的时候可以从离开的地方继续或重新开始。
(与函数生成的局部变量到了函数外失效不同)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
>>> def myGen():
print("Generator is executed.")
yield 1
yield 2


>>> myG =myGen()
>>> next(myG)
Generator is executed.
1
>>> next(myG)
2
>>> next(myG)
Traceback (most recent call last):
File "<pyshell#8>", line 1, in <module>
next(myG)
StopIteration

We can use the generator to realize the Fibonacci sequence.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
>>> def libs():
a = 0
b = 1
while True:
a, b = b, a + b
yield a

# Call the generator.
>>> for each in libs():
if each > 1000:
break
print(each, end=' ')

#Resule
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987

List Comprehension:

Generate a list that can be divided by 2 and not 3.

1
2
3
>>> a = [i for i in range(100) if not (i % 2) and i % 3]
>>> a
[2, 4, 8, 10, 14, 16, 20, 22, 26, 28, 32, 34, 38, 40, 44, 46, 50, 52, 56, 58, 62, 64, 68, 70, 74, 76, 80, 82, 86, 88, 92, 94, 98]

Dictionary Comprehension:

Generate a dictionary that numbers in 0-9 can be distinguished as even or not.

1
2
3
>>> b = {i:i % 2 == 0 for i in range(10)}
>>> b
{0: True, 1: False, 2: True, 3: False, 4: True, 5: False, 6: True, 7: False, 8: True, 9: False}

Set Comprehension:

1
2
3
>> c = {i for i in [1,1,2,3,4,5,5,6,7,8,3,2,1,0]}
>>> c
{0, 1, 2, 3, 4, 5, 6, 7, 8}

String Comprehension: Non-existent.

In string, in “…”, the Python is all string.

Tuple Comprehension:

1
2
3
4
5
6
7
>>> e = (i for i in range(10))
>>> e
<generator object <genexpr> at 0x105a62e60>
>>> next(e)
0
>>> next(e)
1

We can find that it is not tuple comprehension, it is a generator comprehension!

1
2
>>> sum(i for i in range(100) if i % 2)
2500

本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!