[返回值 for element in 可迭代对象 if 条件] ---- 返回一个新列表
提高效率,字节码更少,减少了栈帧
立即返回值
(返回值 for elment in 可迭代对象 if condition)
按需计算(惰性求值,延迟计算),需要的时候才算值
可迭代对象
迭代器
可用next()方法
{返回值 for element in 可迭代对象 if condition}
立即返回一个集合
{返回值 for element in 可迭代对象 if condition}
返回值使用 key:value的形式
立即返回一个字典
通过yield关键字得到一个生成器函数,返回一个生成器对象
延迟计算,惰性求值
yield会暂停函数
def inc():
for i in range(5):
yield i
print(type(inc))
print(type(inc()))
x = inc()
print(type(x))
print(next(x))
for m in x:
print(m, '*')
for m in x:
print(m, '**')
<class 'function'>
<class 'generator'>
<class 'generator'>
0
1 *
2 *
3 *
4 *
生成器函数等价于生成器表达式,只不过生成器函数可以更加复杂
def inc():
for i in range(5):
yield i
#等价于y = (i for i in range(5))
def gen():
print('line 1')
yield 1
print('line 2')
yield 2
print('line 3')
return 3
next(gen()) # line 1
next(gen()) # line 1
g = gen()
print(next(g)) # line 1
print(next(g)) # line 2
#print(next(g)) # StopIteration next无法找到return函数,只认识yield函数
print(next(g, 'End')) #end相当于缺省值
print(next(g, 'End'))
line 1
line 1
line 1
1
line 2
2
line 3
End
End #输出为只有end因为结束后g结束,只返回缺省值end
无限循环:使用yield语句,动一下走一步
def inc():
for x in range(1000):
yield x
#等同于一下语句
def inc():
yield from range(1000)
yield from iterable 是for item in iterable : yield item 形式语法糖
zip(iter1 [,iter2 [...]]) --> zip object
Return a zip object whose .__next__() method returns a tuple where
the i-th element comes from the i-th iterable argument. The .__next__()
method continues until the shortest iterable in the argument sequence
is exhausted and then it raises StopIteration.
返回一个n元组,n为zip括号中可迭代对象数量,每个可迭代对象依次取值,以最短的可迭代对象为准.多余不迭代
原文:https://www.cnblogs.com/agsol/p/11578657.html