多重赋值语义 [英] Multiple assignment semantics

查看:41
本文介绍了多重赋值语义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Python 中可以做到:

a, b = 1, 2(a, b) = 1, 2[a, b] = 1, 2

我使用 dis 检查了生成的字节码,它们是相同的.
那么为什么要允许这样做呢?我会需要其中的一个而不是其他的吗?

解决方案

需要在作业的左侧包含更多结构的一种情况是,当您要求 Python 解压稍微复杂的序列时.例如:

# 有效>>>a, (b, c) = [1, [2, 3]]# 不起作用>>>a, b, c = [1, [2, 3]]回溯(最近一次调用最后一次):文件<stdin>",第 1 行,在 <module> 中ValueError:需要 2 个以上的值才能解包

这在过去证明对我很有用,例如,当使用 enumerate 迭代一系列 2 元组时.类似的东西:

<预><代码>>>>d = { 'a': 'x', 'b': 'y', 'c': 'z' }>>>对于 enumerate(d.iteritems()) 中的 i, (key, value):...打印(我,键,值)(0, 'a', 'x')(1, 'c', 'z')(2, 'b', 'y')

In Python one can do:

a, b   = 1, 2
(a, b) = 1, 2
[a, b] = 1, 2

I checked the generated bytecode using dis and they are identical.
So why allow this at all? Would I ever need one of these instead of the others?

解决方案

One case when you need to include more structure on the left hand side of the assignment is when you're asking Python unpack a slightly more complicated sequence. E.g.:

# Works
>>> a, (b, c) = [1, [2, 3]]

# Does not work
>>> a, b, c = [1, [2, 3]]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: need more than 2 values to unpack

This has proved useful for me in the past, for example, when using enumerate to iterate over a sequence of 2-tuples. Something like:

>>> d = { 'a': 'x', 'b': 'y', 'c': 'z' }
>>> for i, (key, value) in enumerate(d.iteritems()):
...     print (i, key, value)
(0, 'a', 'x')
(1, 'c', 'z')
(2, 'b', 'y')

这篇关于多重赋值语义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆