简体   繁体   中英

Understanding lambda function in python

I was looking at this post:

Python BeautifulSoup: wildcard attribute/id search

in which the answer gives a solution:

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

I thought I understood the lambda function in python. However, when I look at this lambda L: L and L.startswith('date') , I understand that it ultimately returns an id which has a value that contains 'date'. But why is it written as L and L.startswith('date') ? This looks the lambda function is returning a string and a boolean statement.

Can someone explain the logic behind this please ?

and does not actually return a boolean value, that is it doesn't always return True or False.

What it does is it checks the first value for truthiness. A few things are falsy, like None , or 0 , or False , or [] . Other things are truthy.

If the first value is falsy, it is returned. If it's truthy, the second value is returned. If you only consider the truthiness value of the result, then that is the short-circuit implementation of the and logical operator.

The reason why it's used in lambda L: L and L.startswith('date') is to make sure this function doesn't throw an exception in case L is None . If it is, the lambda immediately returns None because it is falsy. Without the check, the startswith() call would throw an exception as None doesn't have that method.

Try out the following on the Python prompt:

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)

As the your linked post stated, the lambda acts as a filter. Its not going to find all div s with the ID of the return value of the lambda ; that wouldn't be useful because IDs need to be unique.

Instead, soup.findall is only going to find the div s whose ID is validated by the lambda , that is any div whose ID is not empty and starts with the string 'date' .

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