0

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

例如:

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

给我:

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

2 回答 2

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

于 2015-05-01T11:54:52.757 回答
2

我不知道你为什么要在这里使用 partial。直接将其编写为函数要容易得多,例如使用 lambda:

functools.filter(lambda x: x == 'hello', xs)
于 2015-05-01T11:54:06.207 回答