|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 游戏小虾米 于 2017-7-30 00:52 编辑
Tip:
生成器就是迭代器
一,理论
yield 生成器的标志
二,应用
1 yield
>>> def myGen():
print('生成器')
yield 1
yield 2
>>> myG = myGen()
>>> myG
<generator object myGen at 0x02E598A0>
>>> myG()
Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
myG()
TypeError: 'generator' object is not callable
>>> next(myG)
生成器
1
>>> next(myG)
2
>>> next(myG)
Traceback (most recent call last):
File "<pyshell#10>", line 1, in <module>
next(myG)
StopIteration
2 斐波那契数列
>>> def libs():
a = 0
b = 1
while True:
a, b = b, a + b
yield a
>>> for each in libs():
if each > 100:
break
print(each, end = ' ')
1 1 2 3 5 8 13 21 34 55 89
3 列表推导式
>>> a = [i for i in range(100) if not(i % 2) and i % 3]
>>>
>>> print(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]
4 字典推导式
>>> 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}
5集合推导式
>>> c = {i for i in [1,2,3,4,4,1,1,2,3,4,5,7,6]}
>>> c
{1, 2, 3, 4, 5, 6, 7}
6 生成器推导式
>>> d = (i for i in range(10))
>>> for each in d:
print(each)
0
1
2
3
4
5
6
7
8
9
>>> d
<generator object <genexpr> at 0x02E62210>
三,课后练习 |
评分
-
查看全部评分
|