让我们建立一个测试图:
import networkx as nx
import random
import matplotlib.pyplot as plt
graph = nx.Graph()
graph.add_edges_from([(1,3), (3,5), (2,4)])
nx.draw(graph, with_labels=True)
plt.show()
Run Code Online (Sandbox Code Playgroud)
现在我们可以从图中的非边列表中选择一条随机边。目前还不完全清楚你提到的概率是多少。由于您添加了一条说明您想使用的评论,因此random.choice我会坚持下去。
def random_edge(graph, del_orig=True):
'''
Create a new random edge and delete one of its current edge if del_orig is True.
:param graph: networkx graph
:param del_orig: bool
:return: networkx graph
'''
edges = list(graph.edges)
nonedges = list(nx.non_edges(graph))
# random edge choice
chosen_edge = random.choice(edges)
chosen_nonedge = random.choice([x for x in nonedges if chosen_edge[0] == x[0]])
if del_orig:
# delete chosen edge
graph.remove_edge(chosen_edge[0], chosen_edge[1])
# add new edge
graph.add_edge(chosen_nonedge[0], chosen_nonedge[1])
return graph
Run Code Online (Sandbox Code Playgroud)
用法示例:
new_graph = random_edge(graph, del_orig=True)
nx.draw(new_graph, with_labels=True)
plt.show()
Run Code Online (Sandbox Code Playgroud)
random.choice如果需要,我们仍然可以在边缘上添加概率分布(numpy.random.choice()例如使用)。