首页 > 解决方案 > 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中是否有与此等效的内置函数?

标签: 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.)


推荐阅读