如何打印生成器的内容? [英] How to print the content of the generator?

查看:232
本文介绍了如何打印生成器的内容?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

N = [1, 2, 3]
print(n for n in N)

结果:

<generator object <genexpr> at 0x000000000108E780>

为什么不打印?:

1
2
3

但是代码:

sum(n for n in N) 

将所有N数相加.

能否请您告诉我为什么sum()有效但print()失败了?

Could you please tell me why sum() worked but print() failed?

推荐答案

这是因为您将生成器传递给了函数,这就是该生成器的__repr__方法返回的内容.如果要打印它将生成的内容,可以使用:

It's because you passed a generator to a function and that's what __repr__ method of this generator returns. If you want to print what it would generate, you can use:

print(*N, sep='\n') # * will unpack the generator

print('\n'.join(map(str, N)))

请注意,一旦检索到生成器的输出以进行打印,该生成器就会被耗尽[em] -尝试对其进行再次迭代将不会产生任何结果.

Note that once you retrieve the generator's output to print it, the generator is exhausted - trying to iterate over it again will produce no items.

这篇关于如何打印生成器的内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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