python - 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
其他测试函数有更多变量。但我会以同样的方式使用它们。
解决方案
您可以重写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
推荐阅读
- apache - Cloudflare SSL 上传失败
- javascript - 如何使用 express 和 node 呈现存在于其中一个子文件夹中并具有自己的样式表和自己的脚本的 html 页面?
- r - R:如何在不重复的情况下对不同列中的值求和?
- python - 是否可以用“所有者”标记测试并在测试失败时记录该所有者?
- locale - GNU gettext msgfilter 程序说“无效的多字节序列”
- android - 投射图像在 Notification、MiniControllerFragment 和 ExpandedControllerActivity 中显示媒体控件
- xamarin - FormsPrievewPackge 包未正确加载 Visual Studio 2017
- elasticsearch - Elasticsearch 6 中对 simple_query_string 查询行为的更改
- bash - Bash 脚本/函数
- javascript - 如何创建异步代码?