在Python函数调用中创建生成器-为什么这样做有效? [英] Creating a generator in a Python function call - why does this work?

查看:62
本文介绍了在Python函数调用中创建生成器-为什么这样做有效?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很困惑为什么此代码有效.在对all()的调用中,我可以使用看起来像代码的语法来生成列表推导,但是除了参数列表对以外,没有任何括号.在参数列表之外执行相同的代码会导致语法错误.在相同的代码上调用print会创建一个生成器,但是不使用yield或(生成器理解括号)?

I am confused why this code works. In a call to all() I can use syntax which appears like code to generate a list comprehension, but without any parentheses other than the pair for the argument list. Executing the same code outside the argument list results in a syntax error. Calling print on the same code results in the creation of a generator, but without using yield or the (generator comprehension parentheses) ?

这种特殊语法仅适用于函数调用吗?或者我缺少某些内容吗?

Is this special syntax applicable to only function calls, or am I missing something?

all(i for i in range(1, 11)) 
# True

print(i for i in range(1, 11))
# the syntax is creating a generator?
# <generator object <genexpr> at 0x00000000CDD7CC00>

i for i in range(1,11)
#   ^
# SyntaxError: invalid syntax

推荐答案

这就是显式定义语法的方式,请参见

This is just how the syntax is explicitly defined, see the original PEP:

如果函数调用具有单个位置参数,则它可以是不带括号的生成器表达式,但是在所有其他情况下,都必须将其括在括号中.

if a function call has a single positional argument, it can be a generator expression without extra parentheses, but in all other cases you have to parenthesize it.

这篇关于在Python函数调用中创建生成器-为什么这样做有效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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