python 3打印生成器 [英] python 3 print generator

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

问题描述

当我处理print()函数(Python 3)时出现问题.

There is a problem when i deal with print() function(Python 3).

当我寻找序列的总和时,我可以使用以下代码模式:

When I'm looking for sum of a series I may use the following code pattern:

>>> sum(i for i in range(101))

但是当我倾向于检查自己制作的系列时:(我选择print()并假设它将逐行打印出来)

But when I tend to check the series that I had made: (I choose print() and assume it will print out line by line)

>>> print(i for i in range(101))

原来变成了没有值返回的生成器对象.因此,我必须使用list()进行序列检查.那是打印功能上的缺陷吗?

It turns out become a generator object without value return. So I have to used list() for series checking. Is that a flaw in print function?

PS:以上内容是构成生成器的示例,不是自然序列的最简单形式,而是复杂序列的骨骼结构.为了方便进行系列值检查,我正在寻找一种逐行打印每个值的方法.

PS: The above written is an example to form a generator, not the simplest form for natural series but the bone structure for complex series. In order for convenience in series values checking, I am looking for a way to print out each value line by line.

推荐答案

sum需要进行一系列迭代处理,而print需要单独的参数进行打印.如果要将生成器的所有项目分别喂入print,请使用*表示法:

sum takes an iterable of things to add up, while print takes separate arguments to print. If you want to feed all the generator's items to print separately, use * notation:

print(*(i for i in range(1, 101)))

不过,无论哪种情况,您实际上都不需要生成器:

You don't actually need the generator in either case, though:

sum(range(1, 101))
print(*range(1, 101))

如果希望将它们放在单独的行上,则表示您希望多次调用print的行为,这意味着您希望看到规则循环的行为:

If you want them on separate lines, you're expecting the behavior of multiple individual calls to print, which means you're expecting the behavior of a regular loop:

for item in generator_or_range_or_whatever:
    print(item)

尽管您还可以选择将'\n'指定为项目分隔符:

though you also have the option of specifying '\n' as an item separator:

print(*generator_or_range_or_whatever, sep='\n')

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

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