如果和内联如果,有哪些优缺点? [英] If and Inline if, what are the advantages and disadvantages?

查看:183
本文介绍了如果和内联如果,有哪些优缺点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对Python中的if和inline之间的区别有点好奇。哪一个更好?

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

是否有任何理由使用 inline if ,除了它更短的事实?

Is there any reason to use inline if, other than the fact that it's shorter?

此声明还有什么问题吗?我收到语法错误: SyntaxError:无法分配给条件表达式

Also, is there anything wrong with this statement? I'm getting a syntax error: SyntaxError: can't assign to conditional expression

a = a*2 if b == 2 else a = a/w


推荐答案

内联 if 表达式的优点是它是一个表达式,这意味着你可以在其他表达式中使用它 - 列表推导,lambda函数等等。

The advantage of the inline if expression is that it's an expression, which means you can use it inside other expressions—list comprehensions, lambda functions, etc.

内联的缺点如果 c $ c>表达式也是它是一个表达式,这意味着你不能在其中使用任何语句。

The disadvantage of the inline if expression is also that it's an expression, which means you can't use any statements inside of it.

缺点的一个完美例子正是如此导致您的错误: a = a / w 是一个语句,因此您无法在表达式中使用它。你必须这样写:

A perfect example of the disadvantage is exactly what's causing your error: a = a/w is a statement, so you can't use it inside an expression. You have to write this:

if b == 2:
    a = a*2
else:
    a = a/w

除了在这种特殊情况下,你只想指定一些东西在任何一种情况下都要 a ,所以你可以这样写:

Except that in this particular case, you just want to assign something to a in either case, so you can just write this:

a = a*2 if b==2 else a/w

至于优势,请考虑这个:

As for the advantage, consider this:

odd_numbers = [number if number%2 else number+1 for number in numbers]

如果没有 if 表达式,则必须将条件包装在一个名为函数 - 这对于非平凡的情况是一件好事,但在这里过于冗长:

Without the if expression, you'd have to wrap the conditional in a named function—which is a good thing for non-trivial cases, but overly verbose here:

def oddify(number):
    if number%2:
        return number
    else:
        return number+1
odd_numbers = [oddify(number) for number in numbers]

此外,请注意以下示例使用 i f (三元条件)表达式,但 if (条件过滤器)子句:

Also, note that the following example is not using an if (ternary conditional) expression, but an if (conditional filter) clause:

odd_numbers = [number for number in numbers if number % 2]

这篇关于如果和内联如果,有哪些优缺点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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