python `in` keyword as a function used in a filter
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.
filter( list1.__contains__, list2 )
is more cleanly written as:
[ v for v in list2 if v in list1 ]
and to show equivalence:
>>> list1 = [2, 4, 6, 8, 10]
>>> list2 = [1, 2, 3, 4, 5]
>>> [ v for v in list2 if v in list1 ]
[2, 4]
You are looking for __contains__
.
>>> [1, 2, 3].__contains__(2)
True
>>> [1, 2, 3].__contains__(4)
False
And for what you want to do:
>>> list1 = [2, 4, 6, 8, 10]
>>> filter(list1.__contains__, [1, 2, 3, 4, 5])
[2, 4]
In general you should use the functions from the operator
module, in this case it would be operator.contains
.
But there is much more efficient way to do this by using sets:
In [1]: list1 = [2, 4, 6, 8, 10]
In [2]: list2 = [1, 2, 3, 4, 5]
In [3]: list(set(list1) & set(list2))
Out[3]: [2, 4]
Note: The &
operator is the intersection.
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
or not
in a function which takes another function as an argument, you can use a lambda function:
>>> list1 = [2, 4, 6, 8, 10]
>>> list2 = [1, 2, 3, 4, 5]
>>> in_check = lambda item: item in list1
>>> filter(in_check, list2)
[2, 4]
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.
精彩评论