在图中找到某种颜色的边缘,python

时间:2012-06-01 08:11:03

标签: python attributes networkx

我使用了颜色属性,在我的图表中着色了两种类型的边。

G.add_edge(fgh,cde,color='blue')

fghcde是用于连接不同元素的变量)(fghcde是循环的一部分,它们的值随每次迭代而变化)

我以gpickle格式保存了该图表,现在我试图从保存的图形中获取某种颜色的边缘。

我想要做的是我得到随机边缘,但它们必须是某种颜色。谢谢你帮助我

1 个答案:

答案 0 :(得分:3)

从pickle加载图表后,您可以先找到所有颜色的所有边缘(参见documentation):

be = []
for e in G.edges_iter():
    if G.edge[e[0]][e[1]]['color'] == 'blue': # or G[e[0]][e[1]]['color']
        be.append(e)

或列表理解:

be = [(n1, n2) for n1, n2 in G.edges_iter() if G.edge[n1][n2]['color'] == 'blue']

然后在random模块的帮助下选择随机边缘,例如choicesample

import random

# Select one random edge...
random_blue_edge = random.choice(be)

# ... or several random edges, 3 in this case
random_blue_edges = random.sample(be, 3)

但是,请务必在致电berandom.choice之前检查random.sample。如果在调用random.choice时序列为空,您将获得IndexError,如果序列短于您要在random.sample中抽样的数字,则会得到{{1} }}