为什么分配给空列表(例如 [] = “")不是错误? [英] Why isn't assigning to an empty list (e.g. [] = "") an error?

查看:48
本文介绍了为什么分配给空列表(例如 [] = “")不是错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 python 3.4 中,我正在输入

In python 3.4, I am typing

[] = "" 

并且它工作正常,没有引发异常.虽然当然 [] 不等于 "" 之后.

and it works fine, no Exception is raised. Though of course [] is not equal to "" afterwards.

[] = ()

也可以正常工作.

"" = []

虽然按预期引发异常,

() = ""

虽然按预期引发异常.发生什么了?

raises an exception as expected though. So, what's going on?

推荐答案

你不是为了平等而比较.您正在分配.

You are not comparing for equality. You are assigning.

Python 允许您分配给多个目标:

Python allows you to assign to multiple targets:

foo, bar = 1, 2

将这两个值分别分配给 foobar.您所需要的只是右侧的 sequenceiterable,以及左侧的名称列表或元组.

assigns the two values to foo and bar, respectively. All you need is a sequence or iterable on the right-hand side, and a list or tuple of names on the left.

当你这样做时:

[] = ""

您将一个 序列(空字符串仍然是序列)分配给一个空名称列表.

you assigned an empty sequence (empty strings are sequences still) to an empty list of names.

这和做的事情本质上是一样的:

It is essentially the same thing as doing:

[foo, bar, baz] = "abc"

你最终得到 foo = "a"bar = "b"baz = "c",但更少字符.

where you end up with foo = "a", bar = "b" and baz = "c", but with fewer characters.

然而,您不能为字符串赋值,因此赋值左侧的 "" 永远不起作用,并且总是语法错误.

You cannot, however, assign to a string, so "" on the left-hand side of an assignment never works and is always a syntax error.

请参阅赋值语句文档一个>:

See the Assignment statements documentation:

赋值语句评估表达式列表(记住这可以是单个表达式或逗号分隔的列表,后者产生一个元组)并将单个结果对象从左到右分配给每个目标列表.

An assignment statement evaluates the expression list (remember that this can be a single expression or a comma-separated list, the latter yielding a tuple) and assigns the single resulting object to each of the target lists, from left to right.

将对象分配给目标列表,可选地括在圆括号或方括号中,递归定义如下.

Assignment of an object to a target list, optionally enclosed in parentheses or square brackets, is recursively defined as follows.

强调我的.

那个 Python 不会为空列表抛出语法错误实际上是一个错误!官方记录的语法不允许空的目标列表,对于空的 () 你确实会得到一个错误.请参阅错误 23275;它被认为是一个无害的错误:

That Python doesn't throw a syntax error for the empty list is actually a bit of a bug! The officially documented grammar doesn't allow for an empty target list, and for the empty () you do get an error. See bug 23275; it is considered a harmless bug:

首先要认识到这已经存在很长时间并且是无害的.

The starting point is recognizing that this has been around for very long time and is harmless.

另见为什么分配给空列表有效而不分配给空元组?

这篇关于为什么分配给空列表(例如 [] = “")不是错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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