我以为我可以通过send
直接访问传递给生成器的值的索引来使我的python(2.7.10)代码更简单,并且对代码运行感到惊讶。然后我发现应用于yield
的索引实际上没有做任何事情,也没有抛出异常:
def gen1():
t = yield[0]
assert t
yield False
g = gen1()
next(g)
g.send('char_str')
但是,如果我尝试将yield
索引三次或更多,我会得到一个例外:
def gen1():
t = yield[0][0][0]
assert t
yield False
g = gen1()
next(g)
g.send('char_str')
抛出
TypeError: 'int' object has no attribute '__getitem__'
这是异常不一致的行为,我想知道是否有关于索引产量实际上在做什么的直观解释?
答案 0 :(得分:13)
您没有编制索引。你正在产生一个清单;表达式yield[0]
实际上与以下相同(但没有变量):
lst = [0]
yield lst
如果您查看next()
返回的内容,您已获得该列表:
>>> def gen1():
... t = yield[0]
... assert t
... yield False
...
>>> g = gen1()
>>> next(g)
[0]
你
异常是由您尝试将订阅应用于包含的yield
整数:
[0]
如果要索引发送到生成器的值,请在0
表达式周围加上括号:
>>> [0] # list with one element, the int value 0
[0]
>>> [0][0] # indexing the first element, so 0
0
>>> [0][0][0] # trying to index the 0
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not subscriptable
演示:
yield