Python中的"x = y或z"分配有什么作用? [英] What does an 'x = y or z' assignment do in Python?

查看:366
本文介绍了Python中的"x = y或z"分配有什么作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如:

def my_function(arg_1=None, arg_2=0):
    determination = arg_1 or arg_2 or 'no arguments given!'
    print(determination)
    return determination

不带任何参数调用时,上述函数将打印并返回'no arguments given!'

When called with no arguments, the above function would print and return 'no arguments given!'

Python为什么要这样做,一个人如何最好地利用这一功能?

Why does Python do this, and how can one best make best use of this functionality?

推荐答案

"or"表达式对赋值的作用:

我们有时会在Python中看到这样的示例,以三元赋值代替条件表达式,(实际上,它有助于启发该语言添加条件语句).

What the "or" expression does on assignment:

We sometimes see examples of this in Python as a substitute for conditional expression with ternary assignments, (in fact, it helped inspire the language to add conditional statements).

x = a or b

如果bool(a)返回False,则为x分配b

下面是一个条件表达式的示例,该条件表达式可以完成相同的操作,但可能不那么神秘.

Here's an example of such a conditional expression that accomplishes the same thing, but with perhaps a bit less mystery.

def my_function(arg_1=None, arg_2=0):
    determination = arg_1 if arg_1 else arg_2 if arg_2 else 'no arguments given!'
    print(determination)
    return determination

过多重复此语法被认为是不好的样式,否则它是好的,对一线客车来说.缺点是它 有点重复.

Repeating this syntax too much is considered to be bad style, otherwise it's OK for one-liners. The downside is that it is a bit repetitive.

如果bool(x)评估True,则基本情况x or y返回x,否则它评估y,(

The base case, x or y returns x if bool(x) evaluates True, else it evaluates y, (see the docs for reference). Therefore, a series of or expressions has the effect of returning the first item that evaluates True, or the last item.

例如

'' or [] or 'apple' or () or set(['banana'])

返回'apple'(第一个评估为True的项目)和

returns 'apple', the first item that evaluates as True, and

'' or [] or ()

返回(),即使它的值为False.

为了对比,如果bool(x)的评估结果为False,则x and y返回x,否则返回y.

For contrast, x and y returns x if bool(x) evaluates as False, else it returns y.

当您认为有条件的and系列中的所有条件都需要评估为True以便控制流沿着该路径前进时,and会这样工作是很有意义的,当您遇到False的项目时,继续评估这些项目毫无意义.

It makes sense that and would work this way when you consider that all of the conditions in a conditional and series needs to evaluate as True for the control flow to proceed down that path, and that it makes no sense to continue evaluating those items when you come across one that is False.

使用and进行分配的实用程序并不像使用or那样显而易见,但是在历史上曾被用于三元分配.也就是说,在此更清晰直接的构造可用之前:

The utility of using and for assignment is not immediately as apparent as using or, but it was historically used for ternary assignment. That is, before this more clear and straightforward construction was available:

a = x if condition else y

与布尔运算符形成的等效项是:

the equivalent formed with boolean operators was:

a = condition and x or z                      # don't do this!

其含义是基于对Python andor评估的充分理解而得出的,但其可读性不及三元条件,因此最好完全避免.

which while the meaning is derivable based on a full understanding of Python and and or evaluation, is not nearly as readable as the ternary conditional, and is best avoided altogether.

使用布尔表达式进行赋值必须仔细.绝对不要使用and进行赋值,这很容易引起错误,这很容易混淆.样式专家会发现使用or进行赋值比使用更冗长的三元(if条件else)更可取,但是我发现它在专业的Python社区中是如此普遍,以至于它被认为是惯用的.

Using Boolean expressions for assignment must be done carefully. Definitely never use and for assignment, which is confusing enough to be quite error-prone. Style mavens will find use of or for assignments less preferable (than the more verbose ternary, if condition else), but I have found that it is so common in the professional Python community that it could be considered idiomatic.

如果您选择使用它,请谨慎行事,因为理解到最终元素(无论达到什么评估)都将始终返回,因此最终元素可能应该是 literal ,这样您就知道您的变量具有很好的默认后备.

If you choose to use it, do so cautiously with the understanding that the final element, if reached, will always be returned regardless of its evaluation, so that final element should probably be a literal, so that you know you have a good default fallback for your variable.

这篇关于Python中的"x = y或z"分配有什么作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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