Python-为什么将此代码视为生成器?

问题描述:

我有一个名为"mb"的列表,其格式为:

I have a list called 'mb', its format is:

['Company Name', 'Rep', Mth 1 Calls, Mth 1 Inv Totals, Mth 1 Inv Vol, Mth 2 

...等等

在下面的代码中,我只是追加了一个新的38 0列表.很好.

In the below code I simply append a new list of 38 0's. This is fine.

但是在下一行中,我得到一个错误: 生成器"对象不支持项目分配

However in the next line I get an error: 'generator' object does not support item assignment

谁能告诉我: 1)如何更正此错误,以及 2)为什么下面的len(mb)-1被认为是生成器.

Can anyone tell me: 1) how to correct this error, and 2) why len(mb)-1 below is considered a generator.

注意:row [0]仅仅是另一个列表中的公司名称".

Note: row[0] is merely a 'Company Name' held in another list.

mb.append(0 for x in range(38))
mb[len(mb)-1][0]=row[0]

实际上,您没有添加38个0的列表:您添加了一个生成器,它将屈服 > 0 38次.这不是您想要的.但是,您可以将mb.append(0 for x in range(38))更改为

In fact, you do not append a list of 38 0s: you append a generator that will yield 0 38 times. This is not what you want. However, you can change can change mb.append(0 for x in range(38)) to

mb.append([0 for x in range(38)]) 
# note the [] surrounding the original generator expression!  This turns it
# into a list comprehension.

或更简单(感谢@John在评论中指出这一点)

or, more simply (thanks to @John for pointing this out in the comments)

mb.append([0] * 38)