python – 为什么不分配给空列表(例如[] =“”)错误?
作者:互联网
在python 3.4中,我正在打字
[] = ""
它工作正常,没有异常.虽然当然[]之后不等于“”.
[] = ()
也行得很好.
"" = []
尽管如此提出例外,
() = ""
尽管如此提出例外.发生什么了?
解决方法:
你不是在比较平等.你正在分配.
Python允许您分配给多个目标:
foo, bar = 1, 2
将两个值分别分配给foo和bar.您只需要右侧的序列或可迭代,以及左侧的名称列表或元组.
当你这样做时:
[] = ""
您将空序列(空字符串仍为序列)分配给空名称列表.
它基本上与做同样的事情:
[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!官方记录的语法不允许空目标列表,而对于empty(),您确实会收到错误.见bug 23275;它被认为是一个无害的bug:
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,syntax,variable-assignment 来源: https://codeday.me/bug/20190917/1809151.html