If and Inline if, what are the advantages and disadvantages?

后端 未结 3 1507
梦如初夏
梦如初夏 2021-01-01 03:36

I\'m a little curious about the difference between if and inline if, in Python. Which one is better?

Is there any reason to use inline if, other than the f

3条回答
  •  旧时难觅i
    2021-01-01 03:42

    The correct way to use the conditional expression is:

    result = X if C else Y
    

    what you have is:

    result = X if C else result = Y
    

    So, you should remove the result = part from there. The major advantage of conditional expression is that, it's an expression. You can use them wherever you would use a normal expression, as RHS of assignment expression, as method/function arguments, in lambdas, in list comprehension, so on. However, you can't just put any arbitrary statements in them, like say print statements.

    Fo e.g. suppose you want all even integers from a list, but for all odd numbers, you want the values as 0. You would use it in list comprehension like this:

    result = [x if x % 2 == 0 else 0 for x in li]
    

提交回复
热议问题