Need to understand Python generator object

久未见 提交于 2019-12-29 07:51:51

问题


In the following:

name = 'TODD'
chars = set('AEIOU')
for ii in range(-1, int(math.copysign(len(name) + 1, -1)), -1):
    if any((cc in chars) for cc in name[ii]):
        print 'Found'
    else:
        print 'Not Found'

I understand that what's inside any(...) is a generator object. What I don't understand is the lack of parentheses - if the parentheses belong to the any() function, shouldn't there be another set of parentheses around the generator expression?

Thanks.


回答1:


The parenthesis can be omitted when used in function calls with only one argument, the generator expression syntax specifically allows for it.

The parentheses can be omitted on calls with only one argument. See section Calls for the detail.




回答2:


You can leave out the parentheses of a generator expression if the expression is the only thing in parentheses already.

From the documentation:

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




回答3:


No, the extra parens are not needed, nor in fact are parens always necessary for the "Boolean expression" you are testing, see these two simple examples:

In [37]: any(i > 10 for i in range(19))
Out[37]: True

In [38]: all(i > 10 for i in range(19))
Out[38]: False

What you have is a function call with a single argument (your generator expression) so no parens are required. See the generator expressions docs for more information.




回答4:


For function calls with just one argument (that generator expression), they aren't required per the docs

The parentheses can be omitted on calls with only one argument. See section Calls for the detail.



来源:https://stackoverflow.com/questions/11672706/need-to-understand-python-generator-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!