Python-为什么将此代码视为生成器? [英] Python - Why is this code considered a generator?

查看:75
本文介绍了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)

这篇关于Python-为什么将此代码视为生成器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆