理解python中的lambda函数

myn*_*EFF 1 python lambda beautifulsoup

我在看这篇文章:

Python BeautifulSoup:通配符属性/ id搜索

答案给出了解决方案:

dates = soup.findAll("div", {"id" : lambda L: L and L.startswith('date')})

我以为我理解了python中的lambda函数.但是,当我看到这个时 lambda L: L and L.startswith('date'),我知道它最终会返回一个id,其值包含'date'.但为什么写成L and L.startswith('date')?这看起来lambda函数返回一个字符串和一个布尔语句.

有人可以解释这背后的逻辑吗?

Rem*_*ich 6

and 实际上并不返回一个布尔值,也就是说它并不总是返回True或False.

它的作用是检查真实性的第一个值.有些东西是假的,比如None,或者0,或者False,或者[].其他的事情是真的.

如果第一个值是假的,则返回.如果它真实,则返回第二个值.如果只考虑结果的真值,那么这就是and逻辑运算符的短路实现.

为什么它在使用的原因lambda L: L and L.startswith('date')是要确保的情况下,此功能不会抛出异常LNone.如果是,则lambda立即返回,None因为它是假的.如果没有检查,则startswith()调用将抛出异常,因为None没有该方法.

在Python提示符下尝试以下内容:

l = lambda L: L and L.startswith('date')

l(None)
l('')
l('does not start with date')
l('date this one does')
l(0)
l(1)
Run Code Online (Sandbox Code Playgroud)