【问题标题】:Can you add a condition into a lambda function?您可以在 lambda 函数中添加条件吗?
【发布时间】:2020-08-20 14:29:58
【问题描述】:

我有以下代码:

clean_tweets['tweet'] = clean_tweets['tweet'].apply(lambda x: remove_noise(x))

我想添加逻辑添加仅当推文为字符串时才执行 remove_noise 的条件

是否有可能实现这一点,有没有其他方法可以做到这一点?

【问题讨论】:

    标签: python function lambda logic


    【解决方案1】:

    可以,可以在Python中使用所谓的三元表达式,比如:

    (result_if_clause_is_true) if (clause) else (result_if_clause_is_false)
    

    在您的具体情况下:

    lambda x: remove_noise(x) if isinstance(x, str) else x
    

    然而,任何比 if/else 操作更复杂的东西都应该成为它自己的函数。

    请注意,此表达式可以在许多其他地方使用,而不仅仅是在 lambdas 中:

    x = y**2 if y < 10 else y/2  # assignment
    

    【讨论】:

      【解决方案2】:
      • lambda x: remove_noise(x) 就是remove_noise

      • 您可能应该将逻辑添加到remove_noise 函数中:

        def remove_noise(x):
            if not isinstance(x, str):
                return x # or None or whatever other value
            # handle the case where x is a string
        

      整体而言:

      def remove_noise(x):
          if not isinstance(x, str):
              return x # or None or whatever othe value
          # handle the case where x is a string
      
      clean_tweets['tweet'] = clean_tweets['tweet'].apply(remove_noise)
      

      【讨论】:

        猜你喜欢
        • 2021-11-26
        • 1970-01-01
        • 2013-07-18
        • 2010-09-24
        • 1970-01-01
        • 2023-03-07
        • 2015-05-20
        • 2011-07-02
        • 1970-01-01
        相关资源
        最近更新 更多