【问题标题】:How to add a conditional statement as an argument to a function in python?如何将条件语句作为参数添加到python中的函数?
【发布时间】:2022-06-30 18:31:19
【问题描述】:

我有以下功能:

def f(loop_condition, count):
    while loop_condition:
        count += 1
        ...

这适用于简单的 True 语句。但是如果我想让我的循环条件是:

count < 3

有没有办法做到这一点?

【问题讨论】:

    标签: python function


    【解决方案1】:

    另一种方法是使用 lambda:

    my_loop_condition = lambda count: count > 3
    

    然后像这样使用它:

    while loop_condition(count)
    

    【讨论】:

      【解决方案2】:

      如果我理解您的问题,这就是解决方案:

      def f(count):
          loopCount=0
          while loopCount<count:
              loupCount += 1
              ...
      

      【讨论】:

        【解决方案3】:

        您可以将 loop_condition 作为字符串传递,然后 eval():

        def f(loop_condition, count):
            while eval(loop_condition):
                count += 1
        print(f('count < 3'))
        

        输出:

        3
        

        【讨论】:

          【解决方案4】:

          您可以将条件作为字符串传递,然后在函数中对其进行评估。例如:

          def func(condition, count):
              while eval(condition):
                  count += 1
              return count
          
          print(func('count < 3', 0))
          

          输出:

          3
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2016-12-11
            • 1970-01-01
            • 2017-06-19
            • 1970-01-01
            • 1970-01-01
            • 2013-07-18
            相关资源
            最近更新 更多