一行 if 条件赋值 [英] One line if-condition-assignment

查看:40
本文介绍了一行 if 条件赋值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码

num1 = 10
someBoolValue = True

如果someBoolValueTrue,我需要将num1 的值设置为20;否则什么都不做.所以,这是我的代码

I need to set the value of num1 to 20 if someBoolValue is True; and do nothing otherwise. So, here is my code for that

num1 = 20 if someBoolValue else num1

有什么办法可以避免 ...else num1 部分以使其看起来更干净吗?相当于

Is there someway I could avoid the ...else num1 part to make it look cleaner? An equivalent to

if someBoolValue:
    num1 = 20

我尝试用 ...else pass 替换它,如下所示:num1=20 if someBoolValue else pass.我得到的只是语法错误.我也不能省略 ...else num1 部分.

I tried replacing it with ...else pass like this: num1=20 if someBoolValue else pass. All I got was syntax error. Nor I could just omit the ...else num1 part.

推荐答案

我认为这在 Python 中是不可能的,因为您实际尝试做的事情可能会扩展到这样的事情:

I don't think this is possible in Python, since what you're actually trying to do probably gets expanded to something like this:

num1 = 20 if someBoolValue else num1

如果你排除了 else num1,你会收到一个语法错误,因为我很确定这个赋值实际上必须返回一些东西.

If you exclude else num1, you'll receive a syntax error since I'm quite sure that the assignment must actually return something.

正如其他人已经提到的,您可以这样做,但这很糟糕,因为您可能会在下次阅读那段代码时感到困惑:

As others have already mentioned, you could do this, but it's bad because you'll probably just end up confusing yourself when reading that piece of code the next time:

if someBoolValue: num1=20

出于完全相同的原因,我不是 num1 = someBoolValue 和 20 或 num1 的忠实粉丝.我必须仔细考虑这条线路在做什么.

I'm not a big fan of the num1 = someBoolValue and 20 or num1 for the exact same reason. I have to actually think twice on what that line is doing.

实际实现您想要做的事情的最佳方法是原始版本:

The best way to actually achieve what you want to do is the original version:

if someBoolValue:
    num1 = 20

之所以是最好的版本,是因为您想要做什么非常明显,并且您不会混淆自己,也不会混淆以后会接触到该代码的其他人.

The reason that's the best verison is because it's very obvious what you want to do, and you won't confuse yourself, or whoever else is going to come in contact with that code later.

另外,作为旁注,num1 = 20 if someBoolValue 是有效的 Ruby 代码,因为 Ruby 的工作方式有点不同.

Also, as a side note, num1 = 20 if someBoolValue is valid Ruby code, because Ruby works a bit differently.

这篇关于一行 if 条件赋值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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