python - 使用 lambda 表达式在 Python 中实现 string contains 函数

标签 python

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

相关文章:

python - Pandas dataframe merge 的性能并不比附加到新列表更好

python - 如何避免使用 numpy.round 进行不正确的舍入?

python - 扭曲 - Python3 类型错误 : __init__() missing 1 required positional argument: 'factory'

python - 循环 Python 中的 ARIMA 预测

python - 安装 web3 时出错 [tester] : Failed building wheel for blake2b-py

python - Xpath 在控制台中正确定位 html 元素,但在 scrapy 响应中使用时返回空数组

python - 子进程中单引号和双引号之间的区别[Python 3.4]

python - 选择至少一次满足条件的所有组

python - 将 html 作为字符串循环一次

python - Python 中的新运算符