Python generator expression parentheses oddity

爱⌒轻易说出口 提交于 2019-12-20 18:01:13

问题


I want to determine if a list contains a certain string, so I use a generator expression, like so:

g = (s for s in myList if s == myString)
any(g)

Of course I want to inline this, so I do:

any((s for s in myList if s == myString))

Then I think it would look nicer with single parens, so I try:

any(s for s in myList if s == myString)

not really expecting it work. Surprise! it does!

So is this legal Python or just something my implementation allows? If it's legal, what is the general rule here?


回答1:


It is legal, and the general rule is that you do need parentheses around a generator expression. As a special exception, the parentheses from a function call also count (for functions with only a single parameter). (Documentation)

Note that testing if my_string appears in my_list is as easy as

my_string in my_list

No generator expression or call to any() needed!




回答2:


It's "legal", and expressly supported. The general rule is "((x)) is always the same as (x)" (even though (x) is not always the same as x of course,) and it's applied to generator expressions simply for convenience.



来源:https://stackoverflow.com/questions/9297653/python-generator-expression-parentheses-oddity

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