标签:obj res image 限制 stop 多次 列表 iter 自定义
在函数中但凡出现yield关键字,再调用函数,就不会继续执行函数体代码,而是会返回一个值。
def func():
print(1)
yield
print(2)
yield
g = func()
print(g)
生成器本质就是迭代器,它只是自定义迭代器的方式
def func():
print('from func 1')
yield 'a'
print('from func 2')
yield 'b'
g = func()
print(F"g.__iter__ == g: {g.__iter__() == g}")
res1 = g.__next__()
print(f"res1: {res1}")
res2 = next(g)
print(f"res2: {res2}")
# next(g) # StopIteration
g.__iter__ == g: True
from func 1
res1: a
from func 2
res2: b
def func():
print('from func 1')
yield 'a'
print('from func 2')
yield 'b'
g = func()
for i in g:
print(i)
print(f"list(func()): {list(func())}")
from func 1
a
from func 2
b
from func 1
from func 2
list(func()): ['a', 'b']
def my_range(start, stop, step=1):
while start < stop:
yield start
start += 1
g = my_range(0, 3)
print(f"list(g): {list(g)}")
list(g): [0, 1, 2]
yield:
yield和return:
t = (i for i in range(10))
print(t)
print(f"next(t): {next(t)}")
<generator object <genexpr> at 0x1101c4888>
next(t): 0
列表推导式相当于直接给你一筐蛋,而生成器表达式相当于给你一只老母鸡。
# 生成器表达式
with open('52.txt','r',encoding='utf8') as f:
nums = [len(line) for line in f]
print(max(nums))
1
# 列表推导式
with open('52.txt','r',encoding='utf8') as f:
nums = (len(line) for line in f)
print(max(nums)) # ValueError: I/O operation on closed file.
标签:obj res image 限制 stop 多次 列表 iter 自定义
原文地址:https://www.cnblogs.com/nickchen121/p/10779713.html