在一行中使用两次表达式 - 作为字符串格式的条件AND?

Ben*_*ler 8 python formatting lambda conditional

我发现在许多不同的项目中,我正在编写大量代码,我需要评估一个(中等复杂,可能代价高昂的评估)表达式然后用它做一些事情(例如用它来进行字符串格式化),但是仅当表达式为True/non-None时.

例如,在很多地方我最终会做如下的事情:

result += '%s '%( <complexExpressionForGettingX> ) if <complexExpressionForGettingX> else ''
Run Code Online (Sandbox Code Playgroud)

...我想这基本上是一个特殊情况,想要返回一个表达式的某些函数,但只有当该表达式为True时,即:

f( e() ) if e() else somedefault
Run Code Online (Sandbox Code Playgroud)

但是没有重新键入表达式(或重新评估它,以防它是一个昂贵的函数调用).

显然,所需的逻辑可以通过各种冗长的方式轻松实现(例如,通过将表达式拆分为多个语句并将表达式分配给临时变量),但这有点蹩脚,因为这似乎是一个非常普遍的问题,并且因为python非常酷(特别是对于功能性的东西)我想知道是否有一个漂亮,优雅,简洁的方法来做到这一点?

我目前最好的选择是定义一个短命的lambda来处理它(比多个语句更好,但有点难以阅读):

(lambda e: '%s ' % e if e else '')( <complexExpressionForGettingX> )
Run Code Online (Sandbox Code Playgroud)

或编写我自己的实用功能,如:

def conditional(expr, formatStringIfTrue, default='')
Run Code Online (Sandbox Code Playgroud)

...但是由于我在许多不同的代码库中执行此操作,我更倾向于使用内置库函数或一些聪明的python语法(如果存在这样的事情)

Tho*_*anz 7

我绝对喜欢单行.但有时它们是错误的解决方案.

在专业软件开发中,如果团队规模大于2,那么您花在理解其他人编写的代码上的时间要多于编写新代码.这里介绍的单行是绝对令人困惑的,所以只做两行(即使你在帖子中提到了多个语句):

X = <complexExpressionForGettingX>
result += '%s '% X  if X else ''
Run Code Online (Sandbox Code Playgroud)

这是清楚,简洁的,每个人都立即明白这里发生了什么.


Ben*_*ler 1

在听到答复后(谢谢大家!),我现在确信,如果不定义新函数(或 lambda 函数),就无法在 Python 中实现我想要的目标,因为这是引入新作用域的唯一方法。

为了最清楚起见,我决定需要将其实现为可重用函数(而不是 lambda),因此为了其他人的利益,我想我应该分享我最终想出的函数 - 它足够灵活,可以处理多个附加格式字符串参数(除了用于决定是否进行格式化的主要参数之外);它还附带了 pythondoc 来显示正确性并说明用法(如果您不确定 **kwargs 是如何工作的,请忽略它,它只是一个实现细节,也是我能看到的实现可选 defaultValue= kwarg 以下的唯一方法格式字符串参数的变量列表)。

def condFormat(formatIfTrue, expr, *otherFormatArgs, **kwargs):
""" Helper for creating returning the result of string.format() on a 
specified expression if the expressions's bool(expr) is True 
(i.e. it's not None, an empty list  or an empty string or the number zero), 
or return a default string (typically '') if not. 

For more complicated cases where the operation on expr is more complicated 
than a format string, or where a different condition is required, use:
(lambda e=myexpr: '' if not e else '%s ' % e)

formatIfTrue -- a format string suitable for use with string.format(), e.g. 
    "{}, {}" or "{1}, {0:d}". 
expr -- the expression to evaluate. May be of any type. 
defaultValue -- set this keyword arg to override

>>> 'x' + condFormat(', {}.', 'foobar')
'x, foobar.'

>>> 'x' + condFormat(', {}.', [])
'x'

>>> condFormat('{}; {}', 123, 456, defaultValue=None)
'123; 456'

>>> condFormat('{0:,d}; {2:d}; {1:d}', 12345, 678, 9, defaultValue=None)
'12,345; 9; 678'

>>> condFormat('{}; {}; {}', 0, 678, 9, defaultValue=None) == None
True

"""
defaultValue = kwargs.pop('defaultValue','')
assert not kwargs, 'unexpected kwargs: %s'%kwargs
if not bool(expr): return defaultValue

if otherFormatArgs:
    return formatIfTrue.format( *((expr,)+otherFormatArgs) )
else:
    return formatIfTrue.format(expr)
Run Code Online (Sandbox Code Playgroud)