gpt4 book ai didi

python - 解包嵌套元组如何在 Python 中工作?

转载 作者:太空宇宙 更新时间:2023-11-03 15:19:18 27 4
gpt4 key购买 nike

尝试从像 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 列表或元组;它只是看起来一样。

关于python - 解包嵌套元组如何在 Python 中工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17641038/

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