代码之家  ›  专栏  ›  技术社区  ›  Rayan CH TFG

需要解释Python中的web抓取lambda函数

  •  0
  • Rayan CH TFG  · 技术社区  · 10 月前

    我正在用Python做Web抓取,我发现了这个:

    products = soup.find_all('li')
    products_list = []
    for product in products:
        name = product.h2.string
        price = product.find('p', string=lambda s: 'Price' in s).string
        products_list.append((name, price))
    

    在这种情况下,我想了解一下lambda函数,非常感谢。

    1 回复  |  直到 10 月前
        1
  •  0
  •   Cheap Nightbot    10 月前

    您正在创建一个lambda(匿名)函数,它接受 s 作为参数,然后检查字符串“Price”是否在 s 或者你可以说 s 包含字符串“Price”。它会回来的 True False 基于此。

    此外,您正在将该函数存储在内部 string 变量。因此,您可以通过该变量调用该lambda函数: string(s) .

    这里有一个例子(如果有帮助的话):

    
    >>> # Create lambda function and store inside `string`
    >>> string = lambda s: "Price" in s
    >>> # Check `string` indeed a lambda function
    >>> string
    <function <lambda> at 0x7f4c0afa1630>
    >>>
    >>> # Call the lambda function with an argument
    >>> # Inside lambda function, now, `s = "Hello, World"` !
    >>> # It will check this: `"Price" in s`, it's not:
    >>> string("Hello, World")
    False
    >>> # Now, `s = "What is the price of milk?"`
    >>> # "Price" and "price" are not same !
    >>> string("What is the price of milk?")
    False
    >>> string("Price of milk is $69.")
    True
    
    

    这个lambda函数与此相同:

    def string(s):
        return "Price" in s