>>> a='test1'
>>> check_for_test1=lambda x:a in x
>>> check_for_test1('test1')
True
>>> a='test2'
>>> check_for_test2=lambda x:a in x
>>> check_for_test2('test1')
False
>>> check_for_test2('test2')
True
>>> check_for_test1('test1')
False
有什么方法可以将 check_for_test1 保留在“原始”测试变量(即 test1)上?
最佳答案
当然,使用闭包:
>>> a='test1'
>>> check_for_test1 = (lambda needle: lambda x: needle in x)(a)
>>> check_for_test1('test1')
True
>>> a = 'foo'
>>> check_for_test1('test1')
True
请注意,您应该避免将 lambda 表达式的结果分配给名称。 lambda
的唯一目的是函数是匿名。这实际上明显违反了 PEP8 风格指南。
这通常称为工厂函数。
我想说,一种更Pythonic的方式是:
def make_checker(needle):
def checker(x):
return needle in x
return checker
这对我来说更清楚。
关于python - 使用 lambda 表达式在 Python 中实现 string contains 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59506963/