简体   繁体   中英

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?

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 . The only purpose of lambda is so a function is anonymous . This is actually explicitly against PEP8 style guidelines.

This is generally called a factory function.

I would say, a more pythonic way would be:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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