gpt4 book ai didi

python - 为什么这本字典解包不起作用

转载 作者:行者123 更新时间:2023-12-02 16:59:33 25 4
gpt4 key购买 nike

以下代码有效:

>>> stack = ['a','b','c']

>>> top, *stack = stack

>>> top

'a'
>>> stack

['b', 'c']

但为什么这不起作用?

>>> dict1={'a':1, 'b':2, 'c':3}

>>> x, **dict1=dict1

SyntaxError: invalid syntax

我不应该期望 x={'a':1} 和 dict1={'b':2, 'c':3} 吗?

最佳答案

如果你想使用字典解包,你可以这样做:(使用Python3.7)

>>> dict1={'a':1, 'b':2, 'c':3}
>>> x, *dict1=dict1.items()
>>> x
('a', 1)
>>> dict1
[('b', 2), ('c', 3)]

dict1.items(),返回一个元组列表,每个元组包含 2 个元素,形式为 (key, value) 对。因此,如果你想将解压后的值转换回字典,你必须这样做 ->

>>> x = [x]  # x = list(x),  won't work for you, because it converts tuple into a list.
# What is actually want is the tuple to be an element of the list.
>>> x # And it works like a charm!
[('a', 1)]

但是,当元组列表被解包时,dict1 包含一个长度为 2 的列表,它们都是元组。因此,将其转换为字典是一种相当直接的方法。

>>> dict1
[('b', 2), ('c', 3)]
>>> dict1 = dict(dict1)
>>> dict1
{'b': 2, 'c': 3}

关于python - 为什么这本字典解包不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54758729/

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