首页 > 解决方案 > python:当涉及 lambda 时,如何将 If else 语句拉入此循环?

问题描述

我有很多有时应该循环有时不应该循环的功能。我想建立一个选项来告诉它循环。这是我的代码。您可以看到每个函数都有该if... else语句。有没有办法将if... else语句放入方法中loop?所以我不必为每个功能重复这些行吗?

import inspect

def test1(b,shouldloop=False):
    if not shouldloop:
        a = b + 1
        print a

    else:
        loop(lambda z: test1(z) , inspect.currentframe().f_code.co_name)

def test2(d,e,shouldloop=False):
    if not shouldloop:
        a = d * e
        print a

    else:
        loop(lambda z: test2(z,e) , inspect.currentframe().f_code.co_name)

def test3(g,h,i,shouldloop=False):
    if not shouldloop:
        a =  g **2 - h + i
        print a

    else:
        loop(lambda z: test3(z,h,i) , inspect.currentframe().f_code.co_name)

def loop(function,c):
    x = [1,2,3,4]
    for i in x:
        function (i)
        print c

所以有时我只需要函数test1不要像这样循环......

test1(2)

输出:

3

有时我需要它像这样循环......

test1('',True)

输出:

2
test1
3
test1
4
test1
5
test1

其他测试函数有更多变量。但我会以同样的方式使用它们。

标签: pythonloopsif-statementlambda

解决方案


您可以重写loop为装饰器以将其添加到任意函数周围:

import functools

def loopable(fnc):  # decorator, takes any function
    @functools.wraps(fnc)
    def fncloop(*args, shouldloop=False, **kwargs):  # take loop switch and arguments for the actual function
        if shouldloop:  # loop logic
            x = [1,2,3,4]
            for i in x:
                fnc(i, *args[1:], **kwargs)  # replace first argument with i
                print(fnc.__name__)
        else:
           fnc(*args, **kwargs)  # call function unconditionally
    return fncloop  # return wrapped function

在定义一个只包含循环体的函数时应用它:

@loopable
def test1(b):
    a = b + 1
    print(a)

现在任何装饰函数都支持shouldloop

>>> test1(2)
3
>>> test1(2, shouldloop=True)
2
test1
3
test1
4
test1
5
test1

对于 Python 2,您必须显式地获取参数kwargs

import functools

def loopable(fnc):
    @functools.wraps(fnc)
    def fncloop(*args, **kwargs):
        if kwargs.pop('shouldloop', False):
            x = [1,2,3,4]
            for i in x:
                fnc(i, *args[1:], **kwargs)  # replace first argument with i
                print(fnc.__name__)
        else:
           fnc(*args, **kwargs)
    return fncloop

推荐阅读