【问题标题】:Incorrect output dictionary from user's input用户输入的输出字典不正确
【发布时间】:2015-10-25 04:39:05
【问题描述】:

我需要输出格式

{0: {1:11,2:13}, 1: {0:11,3:14}}

但结果是

{0: {1:['11'],2:['13']}, 1: {0:['11'],3:['14']}}

使用这个

graph = {}
N,w = map(int,raw_input().split())
# print N, w
for x in range(0,C):
    i,j,c = raw_input().split()
    graph.setdefault(int(i), {}).setdefault(int(j),[]).append(w)
print graph

在输入时

第一行:忽略N=4,而C=4是行数。
第二行:i,j 是顶点,w 是边权重。

4 4
0 1 11
0 2 13
1 0 11
1 3 14

【问题讨论】:

    标签: python python-2.7 python-3.x dictionary graph


    【解决方案1】:

    您在下一行中将列表设置为嵌套字典中的值 -

    graph.setdefault(int(i), {}).setdefault(int(j),[]).append(w)
    

    这就是为什么您在列表中获取值的原因,如果您 100% 确定嵌套字典中的键:值对始终是唯一的,那么您可以简单地将值设置为键。示例 -

    graph.setdefault(int(i), {})[int(j)] = w
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-07-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多