gpt4 book ai didi

python - 在图中查找特定颜色的边,python

转载 作者:行者123 更新时间:2023-11-30 23:43:20 24 4
gpt4 key购买 nike

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

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

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

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

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

最佳答案

从 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)

但是,在调用 random.choicerandom.sample 之前,请务必检查您的 be。如果调用random.choice时序列为空,您将得到一个IndexError,并且如果序列比您想要在random中采样的数字短。示例,您将得到一个ValueError

关于python - 在图中查找特定颜色的边,python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10846674/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com