在`print()`中使用`for`会在Python 3.x上提供一个生成器吗? [英] Use `for` in `print()` will give a generator on Python 3.x?

查看:166
本文介绍了在`print()`中使用`for`会在Python 3.x上提供一个生成器吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么以及如何运作?例如,我正在写这样的列表理解:

Why and how does it works? For example I'm writing a list comprehension like this:

>>> a = (10, 30, 20)
>>> print([q for q in a])
[10, 30, 20]

现在,如果我删除了[],这也将起作用,但是:

At now, if I remove the [], this will also work, but:

>>> a = (10, 30, 20)
>>> print(q for q in a)
<generator object <genexpr> at 0x7fe527d1dca8>

Python是否在此处生成生成器?如果我没有print()这样做:

Does Python make a generator here? And if I do this without print():

>>> a = (10, 30, 20)
>>> b = q for q in a

File "<input>", line 1
  b = q for q in a
          ^
SyntaxError: invalid syntax

我正在考虑,因为(q for q in a)将生成一个生成器,但这是不可能的,但是我没有像这样使用两对():

I'm thinking about because (q for q in a) will make a generator, but that's impossible, however I'm not using two pair of () like:

>>> a = (10, 30, 20)
>>> print((q for q in a)) # here is two pair of `()`
<generator object <genexpr> at 0x7fe527d1dca8>

推荐答案

Python会在这里生成发电机吗?

Does Python make a generator here?

是的.引用生成器表达式

仅具有一个参数的调用可以省略括号.

The parentheses can be omitted on calls with only one argument.


请注意,这是实际语法中唯一的例外情况


Note that this is the only exception from the actual syntax

generator_expression ::=  "(" expression comp_for ")"

所以,当你这样做

b = q for q in a

Python无法解析它,因为它不是有效的Python表达式.这就是为什么您得到SyntaxError的原因.

Python was not able to parse it, as it is not a valid Python expression. That is why you were getting a SyntaxError.

如果您确实想打印生成器表达式中的所有元素,可以像Blckknght所建议的那样将其结果解压缩到print函数中

If you actually wanted to print all the elements from the generator expression, you can unpack the result of it to the print function, as suggested by Blckknght, like this

>>> a = (10, 30, 20)
>>> print(*(q for q in a))
10 30 20

这篇关于在`print()`中使用`for`会在Python 3.x上提供一个生成器吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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