Skip to main content
 首页 » 编程设计

python之如何缩短这个 Python 打印表达式

2025年05月04日9jirigala

我有以下代码处理将两个列表的输出打印为字符串,最终如果列表为空,它应该打印“EMPTY”。 它有效,但我想以某种方式缩短它。

new = [0,1,3] 
old = [0,1,2,3,4,5] 
'to: %s from: %s' % (','.join(map(str,new if len(new) > 0 else ["EMPTY"])),','.join(map(str,old if len(old) > 0 else ["EMPTY"]))) 
#'to: 0,1,3 from: 0,1,2,3,4,5' 

任何建议都会被采纳。

假设:

  • 我必须不使用 .format

更新:

到目前为止,我设法做到了这一点:

'to: %s from: %s' % tuple(','.join(map(str,i if i else ["EMPTY"])) for i in (new, old)) 

请您参考如下方法:

为了使其可读,我只是将格式分解为一个函数:

def fmt(l): 
   return ','.join(map(str, l)) if l else 'EMPTY' 
 
print 'to: %s from: %s' % (fmt(new), fmt(old))