这是成语pythonic? (someBool和“True Result”或“False Result”) [英] Is this idiom pythonic? (someBool and "True Result" or "False Result")

查看:177
本文介绍了这是成语pythonic? (someBool和“True Result”或“False Result”)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

$ p
$ b

而不是:


$

b $ b

  if isUp:
returnUp
else:
returnDown



或甚至:

  if isUp elseDown

代码如下:


$ b b

  return isUp和Up或Down

我可以看到这是相同的结果,但是这是Python中的典型习语吗?如果是,是否有一些性能黑客运行快?

解决方案

a和b或c的成语是如果在Python中,在 PEP 308 发布之前,使用规范的方式表达三元运算书面和实施。这个成语失败的b答案是假的本身;要支持一般情况,可以写

  return(a和[b]或[c])[0] 

拼写的另一种方法是

  return(b,c)[not a] 

引入bool类型,可以重写为

  return(c,b)[bool(a)] 

(如果不清楚,则转换为bool,不知道是bool已经)



今天,如果事情必须是表达式,则应使用条件表达式语法;否则我建议使用if语句。


I just came across this idiom in some open-source Python, and I choked on my drink.

Rather than:

if isUp:
    return "Up"
else:
    return "Down"

or even:

return "Up" if isUp else "Down"

the code read:

return isUp and "Up" or "Down"

I can see this is the same result, but is this a typical idiom in Python? If so, is it some performance hack that runs fast? Or is it just a once-off that needs a code review?

解决方案

The "a and b or c" idiom was the canonical way to express the ternary arithmetic if in Python, before PEP 308 was written and implemented. This idiom fails the "b" answer is false itself; to support the general case, you could write

 return (a and [b] or [c])[0]

An alternative way of spelling it was

 return (b,c)[not a]

which, with the introduction of the bool type, could be rewritten as

 return (c,b)[bool(a)]

(in case it isn't clear: the conversion to bool, and the not operator, is necessary if a is not known to be bool already)

Today, the conditional expression syntax should be used if the thing must be an expression; else I recommend to use the if statement.

这篇关于这是成语pythonic? (someBool和“True Result”或“False Result”)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆