gpt4 book ai didi

python:字典到字典的元组

转载 作者:太空宇宙 更新时间:2023-11-03 12:55:41 24 4
gpt4 key购买 nike

我如何转换字典的元组,如下例所示:

({(1, 2): 3},
{(1, 3): 5},
{(1, 4): 5},
{(2, 4): 5},
{(1, 5): 10},
{(2, 6): 9},
{(1, 6): 9},
{(2, 1): 2},
{(2, 2): 3},
{(2, 3): 5},
{(2, 5): 10},
{(1, 1): 2})

到一个更简单的形式,比如字典:

{(1, 1): 2,
(1, 2): 3,
(1, 3): 5,
(1, 4): 5,
(1, 5): 10,
(1, 6): 9,
(2, 1): 12,
(2, 2): 7,
(2, 3): 7,
(2, 4): 3,
(2, 5): 4,
(2, 6): 2}

最佳答案

你还不能使用字典合并理解,但你可以通过 chain map :

>>> from collections import ChainMap
>>> dict(ChainMap(*dicts))
{(1, 1): 2,
(1, 2): 3,
(1, 3): 5,
(1, 4): 5,
(1, 5): 10,
(1, 6): 9,
(2, 1): 2,
(2, 2): 3,
(2, 3): 5,
(2, 4): 5,
(2, 5): 10,
(2, 6): 9}

注意: collections.ChainMap 是 Python 3.3 中的新内容。

它实际上是 collections.Mapping 的子类,因此根据用例,您甚至可能不需要转换回普通字典。

关于python:字典到字典的元组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43529176/

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