根据我的理解,我可以将字符串与is
和==
进行比较。有没有办法可以部分应用这些功能?
例如:
xs = ["hello", "world"]
functools.filter(functools.partial(is, "hello"), xs)
给我:
functools.filter(functools.partial(is, "hello"), xs)
^
SyntaxError: invalid syntax
答案 0 :(得分:4)
您可以使用operator.eq
:
import operator
import functools
xs = ["hello", "world"]
functools.filter(functools.partial(operator.eq, "hello"), xs)
产量
['hello']
operator.eq(a, b)
相当于a == b
。
答案 1 :(得分:3)
我不知道你为什么要在这里使用部分。将它直接写成函数要容易得多,例如使用lambda:
functools.filter(lambda x: x == 'hello', xs)