Python - Why is this code considered a generator?

2019-07-09 09:03发布

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]

2条回答
甜甜的少女心
2楼-- · 2019-07-09 09:41

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.

查看更多
淡お忘
3楼-- · 2019-07-09 09:54

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)
查看更多
登录 后发表回答