Python部分应用字符串相等函数

时间:2015-05-01 11:50:24

标签: python

根据我的理解,我可以将字符串与is==进行比较。有没有办法可以部分应用这些功能?

例如:

xs = ["hello", "world"]
functools.filter(functools.partial(is, "hello"), xs)

给我:

functools.filter(functools.partial(is, "hello"), xs)
                                    ^
SyntaxError: invalid syntax

2 个答案:

答案 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)
相关问题