我通过向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', John, Debrah, Mary, Greg, Lana, Mathews, Joseph, Bob]
这是使用dict的键添加节点(字符串)
这是使用dict(employees)的值添加边
相关问题 更多 >
编程相关推荐