python基本级别生成器和列表问题 [英] python basic level generator and list questions

查看:64
本文介绍了python基本级别生成器和列表问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

my_nums =(i*i for i in [1,2,3,4,5])
for k in (my_nums):
    print(k)
GG = list(my_nums)

print(GG)

它打印:

1
4
9
16
25
[]

Process finished with exit code 0

我不明白为什么[]值为空(应该为[1,4,9,16,25])?另外,for-loop会将生成器值转换为list吗?

I can't understand why is [] value empty(it should be [1,4,9,16,25])? Also, does for-loop convert generator values to list?

推荐答案

以下是生成器理解:

my_nums =(i*i for i in [1,2,3,4,5])

for k in (my_nums):
    print(k)

因此,当您第一次遍历它并打印值时,生成器将打印它可以生成的每个值. for循环通过调用my_nums.next()并将获得的值分配给k进行工作,然后将其打印出来.引发StopIteration异常时,for循环的迭代停止.

So first time you loop over it and print the values, the generator prints every value it can generate. The for loop works by invoking my_nums.next() and assigning the value obtained to k, which then gets printed. The iteration of the for loop stops when the StopIteration exception is raised.

而且,当在for循环之后使用GG = list(my_nums)时,由于生成器已经用尽并且不再有任何生成器,您会得到一个空列表.

And, when you use GG = list(my_nums) after the for loop, you get an empty list since the generator is already exhausted and it has nothing to generate anymore.

如果要将发生器生成的值存储到list中,则可以直接执行以下操作:

If you want to store the values yielded by the generator into a list you can directly do that as following:

my_nums =(i*i for i in [1,2,3,4,5])
GG = list(my_nums) # no for loop for printing it already

尽管如此,我不确定如果您按照上述方式进行操作,会不会获得任何优势.

Although, I am not sure that performance wise you would gain any advantages if you do it as above.

这篇关于python基本级别生成器和列表问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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