我需要创建这样的东西来表示基于用户输入的有向加权图 -
graph = {
'a': {'b': 1, 'c': 4},
'b': {'c': 3, 'd': 2, 'e': 2},
'c': {},
'd': {'b': 1, 'c': 5},
'e': {'d': -2}
}
到目前为止,
import pprint
graph = {}
values = {}
v = int(input("Enter number of vertices: "))
print("Enter vertices(keys) : ")
for i in range(v):
graph.setdefault(input())
edges = {}
for x in graph:
edges.setdefault(x)
for i in graph:
graph[i] = edges
print("Enter weights: ")
for i in graph:
print(i)
for j in graph[i]:
var = input()
graph[i][j] = var
pprint.pprint(graph)
我试过但由于某种原因,它正在用最后读取的权重替换先前读取的权重。有解决方案吗
答案 0 :(得分:1)
mean(cor(data))
[1] 0.3774926
您正在为for i in graph:
graph[i] = edges
的每个键分配相同的词典(edges
)。因此,当您为其中任何一个值分配值时,您将该值分配给它们的所有。看起来你真正想要的是graph
的副本。在这种情况下,由于您尚未为edges
分配任何可变值,因此浅拷贝就足够了:
edges
答案 1 :(得分:0)
你有缩进错误吗?
而不是
for i in graph:
print(i)
for j in graph[i]:
var = input()
graph[i][j] = var
您可能打算写
for i in graph:
print(i)
for j in graph[i]:
var = input()
graph[i][j] = var