简体   繁体   English

使用 lambda 表达式在 Python 中实现字符串包含函数

[英]Implement string contains function in Python with lambda expression

>>> 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

Is there any way I can keep check_for_test1 to be on the "original" test variable , ie test1?有什么办法可以让 check_for_test1 保持在“原始”测试变量上,即 test1?

Sure, use a closure:当然,使用闭包:

>>> 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

Note, you should avoid assigning the result of a lambda expression to a name .请注意,您应该避免将 lambda 表达式的结果分配给 name The only purpose of lambda is so a function is anonymous . lambda唯一目的是使函数匿名 This is actually explicitly against PEP8 style guidelines.这实际上明确违反了 PEP8 风格指南。

This is generally called a factory function.这通常称为工厂函数。

I would say, a more pythonic way would be:我会说,更pythonic的方式是:

def make_checker(needle):
    def checker(x):
        return needle in x
    return checker

Which is much clearer to me.这对我来说更清楚。

You can capture the original value in the keyword argument with default value:您可以使用默认值捕获关键字参数中的原始值:

a='test1'
check_for_test1=lambda x, a=a:a in x
print( check_for_test1('test1') )
a='test2'
check_for_test2=lambda x, a=a:a in x
print( check_for_test2('test1') )
print( check_for_test2('test2') )
print( check_for_test1('test1') )

Prints:印刷:

True
False
True
True

Note: everything bad about named lambdas in the comments apply.注意:注释中关于命名 lambda 的所有不好的地方都适用。 Don't use them it you don't have to.不要使用它们,您不必使用它们。

If you don't want the functions to change when you update the value of a then use the string itself rather than a variable.如果你不想让功能改变,当你更新的值a则使用字符串本身,而不是一个变量。

check_for_test1=lambda x: 'test1' in x
check_for_test2=lambda x: 'test2' in x

you can use functions with constants, cleaner code:您可以使用带有常量的函数,更简洁的代码:

TEST1 = 'test1'
TEST2 = 'test2'

def check_for_test1(my_str):
    return TEST1 in my_str

def check_for_test2(my_str):
    return TEST2 in my_str

if you want to create dynamically the check methods:如果要动态创建检查方法:

def check_method_creator(my_str):
    def check_method(other_str):
        return my_str in other_str
    return check_method

check_for_test1 = check_method_creator('test1')
check_for_test2 = check_method_creator('test2')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM