【发布时间】:2020-06-27 21:50:34
【问题描述】:
在一个文件中存储多个 networkx 图的最佳方法是什么? This 页面显示了存储一个图形的各种方法,而不是多个图形。有没有办法在例如轻松做到这一点?一个csv文件?我的目标是存储随机生成的图表,以便之后进行一些分析。
谢谢
【问题讨论】:
标签: python python-3.x file-io networkx
在一个文件中存储多个 networkx 图的最佳方法是什么? This 页面显示了存储一个图形的各种方法,而不是多个图形。有没有办法在例如轻松做到这一点?一个csv文件?我的目标是存储随机生成的图表,以便之后进行一些分析。
谢谢
【问题讨论】:
标签: python python-3.x file-io networkx
一种简单的方法是将图形转换为字典列表,可以腌制:
import pickle
import networkx as nx
# dummy graphs
G = nx.complete_graph(4)
H = nx.complete_graph(5)
I = nx.complete_graph(6)
def store_as_list_of_dicts(filename, *graphs):
list_of_dicts = [nx.to_dict_of_dicts(graph) for graph in graphs]
with open(filename, 'wb') as f:
pickle.dump(list_of_dicts, f)
def load_list_of_dicts(filename, create_using=nx.Graph):
with open(filename, 'rb') as f:
list_of_dicts = pickle.load(f)
graphs = [create_using(graph) for graph in list_of_dicts]
return graphs
store_as_list_of_dicts('test.pkl', G,H,I)
graphs = load_list_of_dicts('test.pkl')
替代图构造函数:
graphs = load_list_of_dicts('test.pkl', create_using=nx.MultiDiGraph)
【讨论】: