Python - Why is this code considered a generator?

拈花ヽ惹草 提交于 2020-01-15 03:45:06

问题


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 

...And so on

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

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

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]

回答1:


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.

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

mb.append([0] * 38)



回答2:


You should do this instead:

mb.extend([0]*38)

That way you are appending 38 zeros, rather than appending a single generator expression given by range() (n.b. in Python 2 that gave a list instead).

And using extend instead of append makes the list longer by 38 instead of making it longer by 1 and having the 1 new element be a list of 38 zeros.



来源:https://stackoverflow.com/questions/20123912/python-why-is-this-code-considered-a-generator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!