Python if/else三元表达式中的def

Python if/else三元表达式中的def,python,conditional-operator,Python,Conditional Operator,有没有办法将其转换为: if counts: def a(l): return a_with_counts(l) else: def a(l): return a_without_counts(l) 变成三元表达式 我试过这样的东西 def a(l): return a_with_counts(l) if counts else a_without_counts(l) 但是我不希望每次调用a(l)时都计算if counts,我希望在方法

有没有办法将其转换为:

if counts:
    def a(l):
        return a_with_counts(l)
else:
    def a(l):
        return a_without_counts(l)
变成三元表达式

我试过这样的东西

def a(l):
    return a_with_counts(l) if counts else a_without_counts(l)
但是我不希望每次调用
a(l)
时都计算
if counts
,我希望在方法开始时执行一次,然后每次调用
a(l)
时直接计算分配的函数。这可能吗


谢谢大家!

lambda
中有一个三元

a = lambda counts:a_with_counts if counts else a_without_counts
然后


将创建一个可调用的
a_with_counts
(resp
a_without_counts
)函数。

您可以通过如下定义闭包来实现:

def gen_a(counts):
    return a_with_counts if counts else a_without_counts

a = gen_a(counts)
这相当于写作

a = a_with_counts if counts else a_without_counts

如果您只想调用此函数一次。

为什么要使用三元表达式?为什么不将
counts
作为参数添加到函数
def a(l,counts=True):
等@B001ᛦ, 因为,对于给定的输入,我必须多次运行该方法,
计数
保持不变。@Chris\u Rands我不想每次计算
计数
。对于给定的输入,我想做一次,请注意,Python总是使用def语句,而不是将lambda表达式直接绑定到标识符的赋值语句。@Skandix OP不想每次都计算
counts
该死的,我对
lambda
感到内疚,因为你:)它有在StackOverflow上被很好地提到:看,啊哈!谢谢,这正是我需要的。我得承认我不会想到这个!
a = a_with_counts if counts else a_without_counts