在Python ASTs中,什么时候解包赋值的目标是列表而不是元组?

2024-05-17 02:54:27 发布

您现在位置:Python中文网/ 问答频道 /正文

根据GreenTreeSnakes documentation on Assignment statements报告:

An assignment. targets is a list of nodes, and value is a single node.

Multiple nodes in targets represents assigning the same value to each. Unpacking is represented by putting a Tuple or List within targets.

我的问题是,什么时候解包会将目标放在列表中而不是元组中?给出的示例解压成一个元组


Tags: ofanisvalueondocumentation报告list
1条回答
网友
1楼 · 发布于 2024-05-17 02:54:27

在赋值中,目标既可以是列表,也可以是元组:

a, b, c = value  # assign to a tuple of names
[a, b, c] = value  # assign to a list of names

这种差异对Python来说是表面上的;见Assignment statement reference documentation

演示:

>>> parseprint('[a, b, c] = value')
Module(body=[
    Assign(targets=[
        List(elts=[
            Name(id='a', ctx=Store()),
            Name(id='b', ctx=Store()),
            Name(id='c', ctx=Store()),
          ], ctx=Store()),
      ], value=Name(id='value', ctx=Load())),
  ])

相关问题 更多 >