将Python传递给函数时,为什么要在生成器中省略括号? [英] Why can you omit the surrounding parentheses for generators in Python when passing it into a function?

查看:66
本文介绍了将Python传递给函数时,为什么要在生成器中省略括号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是在用不同的语法在Python中进行实验,以将生成器作为函数的参数传入,我意识到尽管我一直在这样做,

I was just experimenting in Python with different syntax for passing in a generator as an argument to a function, and I realized that although I've been doing this,

>>> sum((j for j in xrange(5)))
10

这同样有效:

>>> sum(j for j in xrange(5))
10

这已在Linux上的Python 2.6.6上进行了测试.到底发生了什么事?只是语法糖吗?毕竟,通常情况下,未解释的生成器对于解释器来说是不可识别的:

This is tested on Python 2.6.6 on Linux. What's going on under the hood? Is it just syntactic sugar? After all, usually an unwrapped generator is indecipherable to the interpreter:

>>> j for j in xrange(5)
  File "<stdin>", line 1
    j for j in xrange(5)
        ^
SyntaxError: invalid syntax

推荐答案

我肯定会阅读 python语法将回答该问题.

I'm sure reading the python grammar will answer that question.

如果您更喜欢普通英语而不是语法: PEP-289 解释.

If you prefer plain English over grammars: PEP-289 explains it.

这篇关于将Python传递给函数时,为什么要在生成器中省略括号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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