一文搞懂 Python 中的 yield
↑↑↑关注后"星标"简说Python
人人都可以简单入门Python、爬虫、数据分析 简说Python推荐 作者 |somenzz 来源 | Python七号
yield 实现生成器
def read(self, sql, params=()):
stmt = ibm_db.prepare(self.connection, sql)
for index, param in enumerate(params):
ibm_db.bind_param(stmt, index + 1, param)
ibm_db.execute(stmt)
row = ibm_db.fetch_tuple(stmt)
while row:
yield row
row = ibm_db.fetch_tuple(stmt)
>>> def iter_fun():
... print("a")
... yield 1
... print("b")
... yield 2
... print("c")
... yield 3
...
>>> iter_fun()
<generator object iter_fun at 0x107e372a0>
>>> for i in iter_fun():
... print(i)
...
a
1
b
2
c
3
>>> x = iter_fun()
>>> x.__next__()
a
1
>>> x.__next__()
b
2
>>> x.__next__()
c
3
>>> x.__next__()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
In [14]: def normal_fun(num):
...: result = []
...: for i in range(0,num):
...: if i%2 == 0:
...: result.append(i)
...: return result
...:
In [14]: def iter_fun(num):
...: for i in range(0,num):
...: if i %2 == 0:
...: yield i
...:
In [15]: %time for i in iter_fun(1000000): a = i
CPU times: user 97 ms, sys: 2.55 ms, total: 99.6 ms
Wall time: 97.2 ms
In [16]: %time for i in normal_fun(1000000): a = i
CPU times: user 115 ms, sys: 13.6 ms, total: 129 ms
Wall time: 128 ms
In [17]: %time for i in normal_fun(100000000): a = i
CPU times: user 10.8 s, sys: 668 ms, total: 11.4 s
Wall time: 11.4 s
In [18]: %time for i in iter_fun(100000000): a = i
CPU times: user 9.1 s, sys: 6.49 ms, total: 9.11 s
Wall time: 9.12 s
with open("file.txt","r") as reader:
for line in reader.readlines():
#do something
pass
with open("file.txt","r") as reader:
for line in reader:
#do something
pass
>>> with open("/etc/passwd","r") as reader:
... dir(reader)
...
['_CHUNK_SIZE', '__class__', '__del__', '__delattr__', '__dict__', '__dir__', '__doc__', '__enter__', '__eq__', '__exit__', '__format__', '__ge__', '__getattribute__', '__getstate__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__lt__', '__ne__', '__new__', '__next__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '_checkClosed', '_checkReadable', '_checkSeekable', '_checkWritable', '_finalizing', 'buffer', 'close', 'closed', 'detach', 'encoding', 'errors', 'fileno', 'flush', 'isatty', 'line_buffering', 'mode', 'name', 'newlines', 'read', 'readable', 'readline', 'readlines', 'reconfigure', 'seek', 'seekable', 'tell', 'truncate', 'writable', 'write', 'write_through', 'writelines']
>>>
yield 可以实现协程
In [20]: def fun():
...: print("a")
...: a = yield 1
...: print("b")
...: print("a = ",a)
...: b = yield a
...: print("c")
...: print("b = ",b)
...:
In [21]: x = fun()
In [22]: x.__next__()
a
Out[22]: 1
In [23]: x.send(4)
b
a = 4
Out[23]: 4
In [24]: x.send(5)
c
b = 5
---------------------------------------------------------------------------
StopIteration Traceback (most recent call last)
<ipython-input-24-9183f5e81876> in <module>
----> 1 x.send(5)
import time
def consume():
r = ''
while True:
n = yield r
if not n:
return
print('[consumer] consuming %s...' % n)
time.sleep(1)
r = 'well received'
def produce(c):
next(c)
n = 0
while n < 5:
n = n + 1
print('[producer] producing %s...' % n)
r = c.send(n)
print('[producer] consumer return: %s' % r)
c.close()
if __name__=='__main__':
c = consume()
produce(c)
[producer] producing 1...
[consumer] consuming 1...
[producer] consumer return: well received
[producer] producing 2...
[consumer] consuming 2...
[producer] consumer return: well received
[producer] producing 3...
[consumer] consuming 3...
[producer] consumer return: well received
[producer] producing 4...
[consumer] consuming 4...
[producer] consumer return: well received
[producer] producing 5...
[consumer] consuming 5...
[producer] consumer return: well received
扫下方二维码添加我的私人微信,可以在我的朋友圈获取最新的Python学习资料,以及近期推文中的源码或者其他资源,另外不定期开放学习交流群,以及朋友圈福利(送书、红包、学习资源等)。
扫码查看我朋友圈
获取最新学习资源
学习更多: 整理了我开始分享学习笔记到现在超过250篇优质文章,涵盖数据分析、爬虫、机器学习等方面,别再说不知道该从哪开始,实战哪里找了
“点赞”传统美德不能丢
评论