在列表中有效但奇怪地使用 yield
Valid, but weird use of yield inside list
我正在玩生成器,突然写了这段代码。
虽然我写了,但我不知道为什么有效,或者为什么有效。
>>> x = (lambda : [(yield 1), (yield 2)])()
>>> next(x)
1
>>> next(x)
2
>>> next(x)
StopIteration
您使用 lambda
语法创建了一个生成器函数。 yield
只是另一个表达式,因此可以在 lambda 内部使用。
你基本上是这样做的:
def foo():
return [(yield 1), (yield 2)]
x = foo()
但都在一个表达式中。
都是yield
表达式returnNone
,所以StopIteration
结果值设置为[None, None]
:
>>> x = (lambda : [(yield 1), (yield 2)])()
>>> next(x), next(x)
(1, 2)
>>> try:
... next(x)
... except StopIteration as si:
... print(si.value)
...
[None, None]
除了使用 next()
,您还可以使用 generator.send()
使 yield
值 return 不同于 None
:
>>> x = (lambda : [(yield 1), (yield 2)])()
>>> next(x) # advance to first yield
1
>>> x.send(42) # set return value for first yield, continue to second
2
>>> try:
... x.send(81) # set return value for second yield
... except StopIteration as si:
... print(si.value)
...
[42, 81]
有效,因为它是合法的 Python 语法。不过用处不大。
我正在玩生成器,突然写了这段代码。
虽然我写了,但我不知道为什么有效,或者为什么有效。
>>> x = (lambda : [(yield 1), (yield 2)])()
>>> next(x)
1
>>> next(x)
2
>>> next(x)
StopIteration
您使用 lambda
语法创建了一个生成器函数。 yield
只是另一个表达式,因此可以在 lambda 内部使用。
你基本上是这样做的:
def foo():
return [(yield 1), (yield 2)]
x = foo()
但都在一个表达式中。
都是yield
表达式returnNone
,所以StopIteration
结果值设置为[None, None]
:
>>> x = (lambda : [(yield 1), (yield 2)])()
>>> next(x), next(x)
(1, 2)
>>> try:
... next(x)
... except StopIteration as si:
... print(si.value)
...
[None, None]
除了使用 next()
,您还可以使用 generator.send()
使 yield
值 return 不同于 None
:
>>> x = (lambda : [(yield 1), (yield 2)])()
>>> next(x) # advance to first yield
1
>>> x.send(42) # set return value for first yield, continue to second
2
>>> try:
... x.send(81) # set return value for second yield
... except StopIteration as si:
... print(si.value)
...
[42, 81]
有效,因为它是合法的 Python 语法。不过用处不大。