"TypeError:“生成器"对象不可下标"当我尝试使用for循环处理二维列表时 [英] "TypeError: 'generator' object is not subscriptable" when I try to deal with 2-dimensional list with for-loop
问题描述
class test(object):
def __init__(self, name):
self.name = ''
testList = [(test("empty") for i in range(3)) for j in range(2)]
for m in range(3):
for n in range(2):
testList[m][n].name = "changed"
我正在尝试检查和更改仅包含对象的二维列表中的项目.我先建立了2d列表,然后尝试使用double for循环影响其中的项目,但它返回TypeError.
I'm trying to check and change items of a 2-dimensional list which contains objects only. I built 2d list first and tried to affect the items in it with double for-loop but it returns TypeError.
Traceback (most recent call last):
File "test.py", line 12, in <module>
testList[m][n].name = "changed"
TypeError: 'generator' object is not subscriptable
我真的不明白这里发生了什么,因为它看起来很简单而且可行.该脚本无法与 testList [0] [0] .name ="changed"
(而不是 testList [m] [n]
)一起运行,因此我怀疑该循环不允许这样运行.但是为什么呢?
I really couldn't understand what's going on here as it seems quite simple and viable. The script could not run with testList[0][0].name = "changed"
(instead of testList[m][n]
) so I suspect that the loop is not allowed to run like this. But why?
推荐答案
您没有创建列表列表,而是创建了生成器对象列表.这些生成器对象处于休眠状态,直到代码对其进行迭代之前它们才处于活动状态.即使那样,您也没有 序列 ,这是使用索引所必需的.为了能够分配给索引,您需要一个 mutable 序列.
You didn't create a list of lists, you created a list of generator objects. Those generator objects are lying dormant, they are not active until code iterates over them. Even then, you don't have a sequence, which is what is required to use indexing. To be able to assign to indexes you need a mutable sequence.
如果要使每个嵌套索引可变,则必须生成列表,而不是生成器.将(...)
括号替换为 [...]
方括号以创建列表理解:
If you want to make each nested index mutable, you have to generate lists, not generators. Replace the (...)
parentheses with [...]
square brackets to create a list comprehension instead:
testList = [[test("empty") for i in range(3)] for j in range(2)]
立即执行列表推导,然后生成一个列表对象.列表是可变序列.
List comprehensions are executed immediately, there and then, producing a list object. Lists are mutable sequences.
这篇关于"TypeError:“生成器"对象不可下标"当我尝试使用for循环处理二维列表时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!