python `in` 关键字作为过滤器中使用的函数
是否可以在过滤器中使用 python 关键字 in
?我知道二元、一元、赋值操作等价于函数调用。
例如,
''!=3
相同
''.__ne__(3)
与in
函数是否有类似的东西 ? 我想做这样的事情。 ..
filter( list1.__in__, list2 )
我想这可以通过编写 in 函数来完成...但我只想知道它是否已经内置。
is it possible to use the python keyword in
in a filter? I know that binary, unary, assignment operations are equivalent to a function call.
such as
''!=3
is the same as
''.__ne__(3)
is there an analogous thing for the in
function?
I want to do something like this. ..
filter( list1.__in__, list2 )
I guess this can be accomplished with writing the in function... but i just want to know if it is already built in or not.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
更简洁地写为:
并显示等价性:
is more cleanly written as:
and to show equivalence:
您正在寻找
__contains__
。对于你想做的事情:
You are looking for
__contains__
.And for what you want to do:
一般来说,您应该使用
operator
模块中的函数,在本例中为operator.contains
。但有一种更有效的方法可以通过使用集合来做到这一点:
注意:
&
运算符是交集。In general you should use the functions from the
operator
module, in this case it would beoperator.contains
.But there is much more efficient way to do this by using sets:
Note: The
&
operator is the intersection.正如 Dan D. 的回答所示,列表理解绝对是做到这一点的最佳方法。不过,在更一般的情况下,如果您想在接受另一个函数作为参数的函数中使用类似
in
或not
的内容,则可以使用 lambda 函数:再次强调,我提出这个只是为了让您了解一般知识;处理这种特定情况的最佳方法肯定是使用列表理解,如 Dan D. 的回答。有关 Python 中 lambda 的更多信息,请访问此处。
A list comprehension, as in Dan D.'s answer, is definitely the best way to do this. In the more general case, though, where you want to use something like
in
ornot
in a function which takes another function as an argument, you can use a lambda function:Again, I present this just for your general knowledge; the best way to handle this specific case is definitely with a list comprehension, as in Dan D.'s answer. More information on lambdas in Python is available here.