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

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

问题描述

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

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

<预><代码>>>>sum(i for i in range(101))

但是当我倾向于检查我制作的系列时:(我选择了 print() 并假设它会一行一行地打印出来)

<预><代码>>>>打印(我在范围内(101))

结果变成了一个没有返回值的生成器对象.所以我必须使用 list() 进行系列检查.这是打印功能的缺陷吗?

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

解决方案

sum 需要将可迭代的东西加起来,而 print 需要单独的参数来打印.如果要将生成器的所有项目分别提供给 print,请使用 * 表示法:

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

不过,在任何一种情况下,您实际上都不需要生成器:

sum(range(1, 101))打印(*范围(1, 101))

如果您希望它们在不同的行上,您会期待多次单独调用 print 的行为,这意味着您期待常规循环的行为:

 用于 generator_or_range_or_whatever 中的项目:打印(项目)

虽然您也可以选择将 ' ' 指定为项目分隔符:

print(*generator_or_range_or_whatever, sep='
')

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))

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))

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: 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 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))

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)

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

print(*generator_or_range_or_whatever, sep='
')

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

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