添加节点和属性列表及KeyError!
我有一些节点,每个节点都有一个叫做'times'的属性列表。在我的模型中,我遇到了一个问题,出现了KeyError'times'的错误。我希望我的图能够保存每个节点的'times'属性列表。我该怎么解决这个问题呢?
import networkx as nx
G = nx.DiGraph()
for u in range(10):
for t in range(5):
if G.has_node(u):
G[u]['times'].append(t)
else:
G.add_node(u,times=[t])
print(G.nodes(data=True))
3 个回答
0
这正是我想要的,挺简单的!
import networkx as nx
G = nx.DiGraph()
for u in range(2):
for t in range(5):
if u in G:
G.node[u]['times'].append(t)
else:
G.add_node(u,times=[t])
print(G.nodes(data=True))
0
试试这个
import networkx as nx
G = nx.DiGraph()
for u in range(10):
for t in range(5):
if G.has_node(u):
if not 'times' in G[u] # this
G[u]['times'] = [] # and this
G[u]['times'].append(t)
else:
G.add_node(u,times=[t])
print(G.nodes(data=True))
1
你可以这样做
G[u].setdefault('times', []).append(t)
而不是这样做
G[u]['times'].append(t)