我通过将对象字典传递给add_nodes_from
函数来添加节点。
然后,我通过将列表传递给add_edges_from
函数来指定边缘。
添加边缘时,它们会创建重复的节点,而不是使用之前已经添加的节点。
import networkx as nx
import matplotlib.pyplot as plt
from Employee import Employee
G = nx.DiGraph()
employees = {
"John": Employee("John"),
"Mathews": Employee("Mathews"),
"Joseph": Employee("Joseph"),
"Lana": Employee("Lana"),
"Debrah": Employee("Debrah"),
"Greg": Employee("Greg"),
"Bob": Employee("Bob"),
"Mary": Employee("Mary"),
}
connections = [
(employees.get("John"), employees.get("Debrah")),
(employees.get("John"), employees.get("Mary")),
(employees.get("Mary"), employees.get("Greg")),
(employees.get("Mary"), employees.get("Lana")),
(employees.get("Mary"), employees.get("Debrah")),
(employees.get("Mathews"), employees.get("Joseph")),
(employees.get("Mathews"), employees.get("Debrah")),
(employees.get("Mathews"), employees.get("Mary")),
(employees.get("Lana"), employees.get("Debrah")),
(employees.get("Greg"), employees.get("Bob")),
]
G.add_nodes_from(employees)
G.add_edges_from(connections)
print(G.nodes)
输出
['John','Mathews','Joseph','Lana','Debrah','Greg','Bob','Mary', 约翰,黛布拉,玛丽,格雷格,拉娜,马修斯,约瑟夫,鲍勃]
答案 0 :(得分:2)
G.add_nodes_from(employees)
这是使用字典(字符串)键添加节点
G.add_edges_from(connections)
这是使用dict(员工)的值添加边