一行if-condition-assignment

问题:一行if-condition-assignment

我有以下代码

num1 = 10
someBoolValue = True

我需要将to的值设置num120if someBoolValueis True; 否则就什么也不做。所以,这是我的代码

num1 = 20 if someBoolValue else num1

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

if someBoolValue:
    num1 = 20

我尝试将其替换为...else passnum1=20 if someBoolValue else pass。我所得到的只是语法错误。我也不能忽略这一...else num1部分。

I have the following code

num1 = 10
someBoolValue = True

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

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

if someBoolValue:
    num1 = 20

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.


回答 0

我认为这在Python中是不可能的,因为您实际尝试执行的操作可能会扩展为以下内容:

num1 = 20 if someBoolValue else num1

如果您排除else num1,则会收到语法错误,因为我非常确定分配实际上必须返回某些内容。

正如其他人已经提到的那样,您可以执行此操作,但是这样做很不好,因为您可能在下次阅读该代码段时最终会感到困惑:

if someBoolValue: num1=20

num1 = someBoolValue and 20 or num1出于完全相同的原因,我不是超级粉丝。我实际上必须对这条线在做什么进行三思。

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

if someBoolValue:
    num1 = 20

最好的版本是因为您想做什么很明显,并且您不会混淆自己,或者其他人以后将与该代码联系。

另外,请注意,num1 = 20 if someBoolValue有效的Ruby代码是有效的,因为Ruby的工作方式略有不同。

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

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

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.

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


回答 1

用这个:

num1 = 20 if someBoolValue else num1

Use this:

num1 = 20 if someBoolValue else num1

回答 2

一行:

if someBoolValue: num1 = 20

但是不要那样做。通常不希望使用此样式。人们更喜欢较长的形式,以保持清晰度和一致性。

if someBoolValue:
    num1 = 20

(同样,应避免使用骆驼帽。因此请使用some_bool_value。)

注意,不存在没有部分的内联表达式 不存在,因为如果谓词为false,则不会有返回值。但是,在所有情况下,表达式必须具有明确定义的返回值。这与Ruby或Perl中的用法不同。some_value if predicateelse

In one line:

if someBoolValue: num1 = 20

But don’t do that. This style is normally not expected. People prefer the longer form for clarity and consistency.

if someBoolValue:
    num1 = 20

(Equally, camel caps should be avoided. So rather use some_bool_value.)

Note that an in-line expression some_value if predicate without an else part does not exist because there would not be a return value if the predicate were false. However, expressions must have a clearly defined return value in all cases. This is different from usage as in, say, Ruby or Perl.


回答 3

您可以使用以下之一:

(falseVal, trueVal)[TEST]

TEST and trueVal or falseVal

you can use one of the following:

(falseVal, trueVal)[TEST]

TEST and trueVal or falseVal

回答 4

不,我想您希望类似的方法num1 = 20 if someBoolValue可以工作,但是不行。我认为最好的方法就是if编写语句:

if someBoolValue:
    num1 = 20

No. I guess you were hoping that something like num1 = 20 if someBoolValue would work, but it doesn’t. I think the best way is with the if statement as you have written it:

if someBoolValue:
    num1 = 20

回答 5

num1 = 10 + 10*(someBoolValue is True)

那是我新的最终答案。先前的答复如下,并且对于所述问题过大。Getting_too_clever == not Good。这是先前的答案…如果您想为Truecond 添加一件事,为False:添加另一件事,还是不错的:

num1 = 10 + (0,10)[someBoolValue is True]

您提到num1的值已经应该保留。我假设num1 = 10因为这是该帖子的第一条语句,所以要进行的操作20是add 10

num1 = 10
someBoolValue = True

num1 = 10 + (0,10)[someBoolValue is True]

print(f'num1 = {num1}\nsomeBoolValue = {someBoolValue}')

产生了这个输出

num1 = 20
someBoolValue = True
num1 = 10 + 10*(someBoolValue is True)

That’s my new final answer. Prior answer was as follows and was overkill for the stated problem. Getting_too_clever == not Good. Here’s the prior answer… still good if you want add one thing for True cond and another for False:

num1 = 10 + (0,10)[someBoolValue is True]

You mentioned num1 would already have a value that should be left alone. I assumed num1 = 10 since that’s the first statement of the post, so the operation to get to 20 is to add 10.

num1 = 10
someBoolValue = True

num1 = 10 + (0,10)[someBoolValue is True]

print(f'num1 = {num1}\nsomeBoolValue = {someBoolValue}')

produced this output

num1 = 20
someBoolValue = True

回答 6

num1 = 20 * someBoolValue or num1
num1 = 20 * someBoolValue or num1

回答 7

如果希望在某个布尔值为true的情况下调用方法,则可以else None终止三进制。

>>> a=1
>>> print(a) if a==1 else None
1
>>> print(a) if a==2 else None
>>> a=2
>>> print(a) if a==2 else None
2
>>> print(a) if a==1 else None
>>>

If you wish to invoke a method if some boolean is true, you can put else None to terminate the trinary.

>>> a=1
>>> print(a) if a==1 else None
1
>>> print(a) if a==2 else None
>>> a=2
>>> print(a) if a==2 else None
2
>>> print(a) if a==1 else None
>>>

回答 8

如果肯定要为您编写一行代码,Python 3.8会引入亲切的表达式,被称为“海象运算符”。

:=

someBoolValue and (num := 20)

如果第一个布尔表达式为,20则将分配给。赋值必须在括号内,否则会出现语法错误。numTrue

num = 10
someBoolValue = True

someBoolValue and (num := 20)
print(num) # 20

num = 10
someBoolValue = False

someBoolValue and (num := 20)
print(num) # 10

If one line code is definitely going to happen for you, Python 3.8 introduces assignment expressions affectionately known as “the walrus operator”.

:=

someBoolValue and (num := 20)

The 20 will be assigned to num if the first boolean expression is True. The assignment must be inside parentheses here otherwise you will get a syntax error.

num = 10
someBoolValue = True

someBoolValue and (num := 20)
print(num) # 20

num = 10
someBoolValue = False

someBoolValue and (num := 20)
print(num) # 10

回答 9

对于来自Google的未来旅行者来说,这是一种新方法(可从python 3.8开始使用):

b = 1
if a := b:
    # this section is only reached if b is not 0 or false.
    # Also, a is set to b
    print(a, b)

For the future time traveler from google, here is a new way (available from python 3.8 onward):

b = 1
if a := b:
    # this section is only reached if b is not 0 or false.
    # Also, a is set to b
    print(a, b)

回答 10

如果需要,您绝对可以使用num1 =(如果someBoolValue为20,则为num1)。

You can definitely use num1 = (20 if someBoolValue else num1) if you want.


回答 11

这是我可以建议的。使用另一个变量派生if子句并将其分配给num1。

码:

num2 =20 if someBoolValue else num1
num1=num2

Here is what i can suggest. Use another variable to derive the if clause and assign it to num1.

Code:

num2 =20 if someBoolValue else num1
num1=num2

回答 12

其他方式 num1 = (20*boolVar)+(num1*(not boolVar))

Another way num1 = (20*boolVar)+(num1*(not boolVar))


回答 13

您可以这样进行。

try:
    a = [i for i in [20] if False][0]
except IndexError:
    print("Do what ever you want here")

您可以通过这种方式解决问题,但是,使用“ try / except block”不是python的最佳实践。

You can do it this way.

try:
    a = [i for i in [20] if False][0]
except IndexError:
    print("Do what ever you want here")

You can solve your problem this way but, using ‘try/except block’ is not the best practice for python.