gpt4 book ai didi

python - 反转 defaultdict(dict)

转载 作者:行者123 更新时间:2023-11-28 22:27:41 27 4
gpt4 key购买 nike

如果我有一个 defaultdict(dict):

defaultdict("dict"), {'NYC': {'LA': '3000'}, 'SanFrancisco': {'Houston': '1000'}, 'LA': {'Detroit': '200', 'Ames': '300', 'SanFrancisco': True}, 'Austin': {'Houston': '500'}})

我怎样才能“扭转弧线”?还是本网站的第 3 步? http://www.geeksforgeeks.org/connectivity-in-a-directed-graph/

示例输出:

# edited for more clarity
defaultdict(<class 'dict'>,
{'Ames': {'LA': '300'},
'Detroit': {'LA': '200'},
'Houston': {'Austin': '500', 'SanFrancisco': '1000'},
'LA': {'NYC': '3000'},
'SanFrancisco': {'LA': True}})

用于转置图形:https://en.wikipedia.org/wiki/Transpose_graph

附言我想将我的反转图保留为 defaultdict(dict)。谢谢!

最佳答案

嵌套的 defaultdict 是一个二维数据结构(对于每个源城市,可能有多个目的地)。因此,使用嵌套的 for 循环来遍历数据并重新插入到一个新的 defaultdict 中是有意义的(交换源和目标):

>>> from collections import defaultdict

>>> start = defaultdict(dict, {'NYC': {'LA': '3000'}, 'SanFrancisco': {'Houston': '1000'}, 'LA': {'Detroit': '200', 'Ames': '300', 'SanFrancisco': True}, 'Austin': {'Houston': '500'}})

>>> goal = defaultdict(dict)
>>> for source, dests in start.items():
for dest, distance in dests.items():
goal[dest][source] = distance

>>> goal
defaultdict(<class 'dict'>, {'LA': {'NYC': '3000'}, 'Houston': {'SanFrancisco': '1000', 'Austin': '500'}, 'Detroit': {'LA': '200'}, 'Ames': {'LA': '300'}, 'SanFrancisco': {'LA': True}})

关于python - 反转 defaultdict(dict),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43968088/

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