我正在尝试使用 NetworkX 中的 if 语句比较两个节点值。为此,我的图(G)和图(G1)的图结构如下所示:
import networkx as nx
#Define Graph G
G = nx.DiGraph()
G.add_edge('x','a', dependency=0.4)
G.add_edge('x','b', dependency=0.7)
G.add_edge('b','a', dependency=0.3)
G.add_node('x', value=10)
G.add_node('a', value=15)
G.add_node('b', value=20)
#Define Graph G1
G1 = nx.DiGraph()
G1.add_edge('x','a', dependency=0.4)
G1.add_edge('x','b', dependency=0.7)
G1.add_edge('b','a', dependency=0.3)
G1.add_node('x1', value=10)
G1.add_node('a1', value=15)
G1.add_node('b1', value=20)
现在,我只想比较 G.node(x) 和 G1.node(x1) 的两个节点属性,如果它们相同,则执行某些操作:
if G.nodes(['x']['value']) == G1.nodes['x1']['value']:
print("Both values are the same!")
但我不断收到以下错误消息:
TypeError: list indices must be integers or slices, not str
有人可以帮我解决这个问题吗?
最佳答案
if (G.nodes['x']['value'] == G1.nodes['x1']['value']):
print("Both values are the same!")
访问节点时没有括号。
关于python - 使用 Python 比较 NetworkX 中的节点值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60372605/