编程语言
首页 > 编程语言> > 如何在Python中解压缩嵌套元组?

如何在Python中解压缩嵌套元组?

作者:互联网

尝试从数据结构中将t =((“” foo“,),)的值分配给变量,我发现以下工作原理:

((var,),) = t   # or [[var]] = t

我不知道它是如何工作的. Python是否在左侧创建元组/列表?
在源中对相关部分的引用也将被理解.

解决方法:

Python将递归地从右侧解压缩值.

没有创建元组.而是由编译器解释左侧语法,以弄清楚如何从右侧分配序列.

要查看实际效果,请分解工作分配代码:

>>> def foo():
...     ((var,),) = t
... 
>>> import dis
>>> dis.dis(foo)
  2           0 LOAD_GLOBAL              0 (t)
              3 UNPACK_SEQUENCE          1
              6 UNPACK_SEQUENCE          1
              9 STORE_FAST               0 (var)
             12 LOAD_CONST               0 (None)
             15 RETURN_VALUE        

在这里,t被解压两次以存储在var中;编译器确定左侧为嵌套序列,然后将其编译为两个UNPACK_SEQUENCE字节码.

这些都记录在assignment statement reference中:

Assignment is defined recursively depending on the form of the target (list).

Assignment of an object to a target list is recursively defined as follows.

  • If the target list is a single target: The object is assigned to that target.
  • If the target list is a comma-separated list of targets: The object must be an iterable with the same number of items as there are targets in the target list, and the items are assigned, from left to right, to the corresponding targets.

Assignment of an object to a single target is recursively defined as follows.

[…]

  • If the target is a target list enclosed in parentheses or in square brackets: The object must be an iterable with the same number of items as there are targets in the target list, and its items are assigned, from left to right, to the corresponding targets.

最后一部分特别告诉您,左侧不被解释为Python列表或元组.看起来一样.

标签:variable-assignment,python
来源: https://codeday.me/bug/20191030/1969584.html