irf*_*ari 4 python nodes networkx
我想从图中提取两个节点,因为它们不应该连接,即它们之间不存在直接边缘.我知道我可以使用"random.choice(g.edges())获得随机边缘",但这会给我连接的随机节点.我想要一对未连接的节点(一对未连接的边).帮助我...伙计们
Mar*_*ina 10
简单!:)
抓取一个随机节点 - 然后从不包括邻居和自身的节点列表中选择一个随机节点.代码说明如下.:)
import networkx as nx
from random import choice
# Consider this graph
#
# 3
# |
# 2 - 1 - 5 - 6
# |
# 4
g = nx.Graph()
g.add_edge(1,2)
g.add_edge(1,3)
g.add_edge(1,4)
g.add_edge(1,5)
g.add_edge(5,6)
first_node = choice(g.nodes()) # pick a random node
possible_nodes = set(g.nodes())
neighbours = g.neighbors(first_node) + [first_node]
possible_nodes.difference_update(neighbours) # remove the first node and all its neighbours from the candidates
second_node = choice(list(possible_nodes)) # pick second node
print first_node, second_node
Run Code Online (Sandbox Code Playgroud)
小智 1
我不知道那个库,但我猜你可以执行以下操作:
n1 = random.choice(g.nodes())
n2 = random.choice(g.nodes())
while (n1 == n2 or any of the edges of n1 lead to n2):
n2 = random.choice(g.nodes())
enjoy(yourNodes)
Run Code Online (Sandbox Code Playgroud)
干杯