gpt4 book ai didi

python - 为什么字典可以解包为元组?

转载 作者:IT老高 更新时间:2023-10-28 21:44:46 25 4
gpt4 key购买 nike

今天,我看到一个没有抛出异常的语句。谁能解释一下它背后的理论?

>>> x, y = {'a': 2, 'b': 5}
>>> x
'a'
>>> y
'b'

最佳答案

在 Python 中,每个 iterable可以解包1:

>>> x,y,z = [1, 2, 3]  # A list
>>> x,y,z
(1, 2, 3)
>>> x,y,z = 1, 2, 3 # A tuple
>>> x,y,z
(1, 2, 3)
>>> x,y,z = {1:'a', 2:'b', 3:'c'} # A dictionary
>>> x,y,z
(1, 2, 3)
>>> x,y,z = (a for a in (1, 2, 3)) # A generator
>>> x,y,z
(1, 2, 3)
>>>

此外,因为遍历字典只返回它的键:

>>> for i in {1:'a', 2:'b', 3:'c'}:
... print i
...
1
2
3
>>>

解包字典(迭代它)同样只解包它的键。


1其实我应该说每个iterable都可以解包只要要解包的名字等于iterable的长度:

>>> a,b,c = [1, 2, 3]  # Number of names == len(iterable)
>>>
>>> a,b = [1, 2, 3] # Too few names
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: too many values to unpack (expected 2)
>>>
>>> a,b,c,d = [1, 2, 3] # Too many names
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: need more than 3 values to unpack
>>>

但这仅适用于 Python 2.x。在 Python 3.x 中,您有 extended iterable unpacking ,它允许您将任何(有限)大小的可迭代对象解压缩为您需要的名称:

>>> # Python 3.x interpreter
...
>>> a, *b, c = [1, 2, 3, 4]
>>> a, b, c
(1, [2, 3], 4)
>>>
>>> a, *b = [1, 2, 3, 4]
>>> a, b
(1, [2, 3, 4])
>>>
>>> *a, b, c = [1, 2, 3, 4]
>>> a, b, c
([1, 2], 3, 4)
>>>

关于python - 为什么字典可以解包为元组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23268615/

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