隐式定义生成器的收益率?
Yield in Implicitly Defined Generator?
To avoid interfering with the expected operation of the generator expression itself, yield and yield from expressions are prohibited in the implicitly defined generator
这是什么意思?
这意味着你不能做类似的事情:
sum(yield x*x for x in range(10))
这显然是因为显式 yield
与允许的 sum(x*x for x in range(10))
中的隐式 yield 交互的方式很难推理,而且一旦您开始使用高级技术,情况只会变得更糟像 generator.send
和 generator.throw
.
这是指在生成器表达式中使用 yield 表达式,例如:
>>> g = ((yield x**2) for x in [1,2,3])
>>> list(g)
[1, None, 4, None, 9, None]
或者:
>>> t = "hello", "world"
>>> g = ((yield from t) for x in 'xyz')
>>> list(g)
['hello', 'world', None, 'hello', 'world', None, 'hello', 'world', None]
此语法是 deprecated in Python 3.7 and will be a SyntaxError
in Python 3.8+. See bpo10544 以获取更多详细信息。
To avoid interfering with the expected operation of the generator expression itself, yield and yield from expressions are prohibited in the implicitly defined generator
这是什么意思?
这意味着你不能做类似的事情:
sum(yield x*x for x in range(10))
这显然是因为显式 yield
与允许的 sum(x*x for x in range(10))
中的隐式 yield 交互的方式很难推理,而且一旦您开始使用高级技术,情况只会变得更糟像 generator.send
和 generator.throw
.
这是指在生成器表达式中使用 yield 表达式,例如:
>>> g = ((yield x**2) for x in [1,2,3])
>>> list(g)
[1, None, 4, None, 9, None]
或者:
>>> t = "hello", "world"
>>> g = ((yield from t) for x in 'xyz')
>>> list(g)
['hello', 'world', None, 'hello', 'world', None, 'hello', 'world', None]
此语法是 deprecated in Python 3.7 and will be a SyntaxError
in Python 3.8+. See bpo10544 以获取更多详细信息。