gpt4 book ai didi

python - 为什么分配给空列表(例如 [] = "")不会出错?

转载 作者:IT老高 更新时间:2023-10-28 21:06:19 25 4
gpt4 key购买 nike

在 python 3.4 中,我正在输入

[] = "" 

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

[] = ()

也可以正常工作。

"" = []

按预期引发异常,

() = ""

尽管按预期引发了异常。发生什么了?

最佳答案

你不是在比较平等。您正在分配

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

foo, bar = 1, 2

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

当你这样做时:

[] = ""

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

本质上和做是一样的:

[foo, bar, baz] = "abc"

你以 foo = "a"bar = "b"baz = "c" 结尾,但更少字符。

但是,您不能对字符串进行赋值,因此赋值左侧的 "" 永远不会起作用,并且始终是语法错误。

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 不会为空列表抛出语法错误实际上是一个错误!官方记录的语法不允许空的目标列表,并且对于空的 () 你会得到一个错误。见 bug 23275 ;它被认为是无害的错误:

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

另见 Why is it valid to assign to an empty list but not to an empty tuple?

关于python - 为什么分配给空列表(例如 [] = "")不会出错?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30147165/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com