0

I have created a script in python using BeautifulSoup to parse some information from some html snippet. It is working fine when I use list comprehension. My goal here is to do the same using lambda expression. I've heard that the two list comprehension and lambda expression can work identically. However, I can't find any idea as to how I could apply lambda function to achieve the same result that I've got using list comprehension. Any help on this will be highly appreciated.

Here is what my code so far:

from bs4 import BeautifulSoup

content="""
 <td align="right">0.00 %</td>,
 <td align="right">2.52</td>,
 <td align="right">1.79</td>,
 <td align="right">1.79 % </td>,
 <td align="right">0.72</td>,
 <td align="right">1.08 %</td>
"""
soup = BeautifulSoup(content,"lxml")
data = [item.text for item in soup.find_all("td")] #it is doing fine
# data = "wish to do the same like above using lambda"
print(data)
SIM
  • 21,997
  • 5
  • 37
  • 109

1 Answers1

2

The most I can think of is applying a lambda using map:

map(lambda x: x.text,soup.find_all("td"))

This is a generator expression in Python 3, so either iterate it or list() around it. As mentioned in the commons, a map is more of an afterthought of the creator of Python, you can explicitly write out a generator expression by substituting the [] for () in your comprehension.

kabanus
  • 24,623
  • 6
  • 41
  • 74