Python 生成器表达式括号奇怪
我想确定列表是否包含某个字符串,所以我使用生成器表达式,如下所示:
g = (s for s in myList if s == myString)
any(g)
当然我想内联它,所以我这样做:
any((s for s in myList if s == myString))
然后我认为使用单括号看起来会更好,所以我尝试:
any(s for s in myList if s == myString)
不真的很期待它能发挥作用。惊喜!确实如此!
那么这是合法的 Python 还是只是我的实现允许的?如果合法,那么这里的一般规则是什么?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是合法的,一般规则是生成器表达式确实需要括号。作为一个特殊的例外,函数调用中的括号也计数(对于仅具有单个参数的函数)。 (文档)
请注意,测试
my_string
是否出现在中 一样简单!
my_list 就像不需要生成器表达式或调用
any()
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 inmy_list
is as easy asNo generator expression or call to
any()
needed!这是“合法的”,并且得到明确支持。一般规则是“
((x))
始终与(x)
相同”(尽管(x)
并不总是当然与x
相同),并且将其应用于生成器表达式只是为了方便。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 asx
of course,) and it's applied to generator expressions simply for convenience.