python - Python中有单行闭包函数吗?
问题描述
我一直在充分利用这个通常在我需要的时候定义的函数,因为它太小了:
def func(_lambda, *args):
return _lambda(*args)
IE
[func((lambda x: (("fizbuz" if x%5==0 else "fiz")
if x%3==0 else ("buz" if x%5==0 else x))), x)
for x in list(range(1,101))]
Python中是否有与此等效的内置函数?
解决方案
看看functools.partial
(文档)。
从广义上讲,您正在查看以下内容:
from functools import partial
def func(*args):
# your logic here
myfunc = partial(func, *args)
如果需要,可以将其他参数传递给myfunc
;文档中的示例很好地证明了这一点:
>>> from functools import partial
>>> basetwo = partial(int, base=2)
>>> basetwo('10010')
18
None of this is necessary for your case, since moving your fizzbuzz logic out of the list comprehension and into a separate function allows you to use it like this (which, in my opinion, is much easier to follow):
[fizzbuzz(x) for x in range(1, 101)]
(The partial is a handy trick to have up your sleeve though.)
推荐阅读
- kubernetes - Kubernetes入口websockets连接问题
- html - 如何根据 HTML 中另一个视频的暂停时间更改视频
- flutter - 如何制作像“斑马”这样的交替颜色数据表行
- json - 文件移动/复制操作后 Jupyter Notebooks 不可读
- android - 如何将包含在 Singlechild Scrollview 中的列内的 Widget 居中?
- python - Pygame按键问题
- django - 如何在 django 中获得今天的第几周
- reactjs - props 无法与 componentDidUpdate 一起使用。(现金污染)
- java - 重做循环代码的缩短乘法
- angular - Angular 中 .sort() 函数的 Karma-Jasmine 中的单元测试故障排除