【问题标题】:Creating a random edge to a neighbor that excludes one particular node in Networkx为邻居创建一条随机边,排除 Networkx 中的一个特定节点
【发布时间】:2015-12-04 05:55:10
【问题描述】:

我正在尝试编写一个函数,该函数将从图中的特定节点中删除 2 条随机边,但具有另一个特定节点的边除外。我正在使用 Python Networkx 包。这是我的代码:

close = nx.closeness_centrality(self.combined_network) #This calculates closeness
self.most_central_node = max(close.items(), key=itemgetter(1))[0] identifies the maximum centrality
self.combined_network.add_edge(self.most_central_node, 'bad_apple_Bad_apple') adds an edge from the most central node to a specific node

接下来我想做的是让 self.most_central_node 打破 2 条边(随机),但不要打破我刚刚用“bad_apple_Bad_apple”创建的那个。我首先尝试使用以下方法选择 most_central_node 的邻居:

Neighb = (B.neighbors(most_central_node))

这行得通,但它返回一个列表。现在我正在尝试构建没有“bad_apple_Bad_apple”的列表

我试过了:

n2 = B.node['bad_apple_0']
n3 = (item for item in Neighb if item not in n2)

我认为这行不通。当我在控制台中打印 n3 时,我得到:
<generator object <genexpr> at 0x00000000203845E8>

我做错了什么?然后我需要随机选择其中的 2 个来要求 most_central_node 与它们断开边缘。也有人能指点一下吗?

【问题讨论】:

  • n3 给你一个生成器表达式。您可以使用n3.next() 调用下一个值或使用list(n3) 获取所有值。对于删除边:您可以获取节点的边列表并使用numpy.random.choice(edge_list, p=edge_probs),其中 edge_probs 是每个条目的概率列表。将您希望保留的边的概率设置为 0,并将其余边的概率设置为相等。
  • 谢谢@Scott。这很有帮助,但在我需要消除“bad_apple_Bad_apple”节点的边缘被移除的可能性的意义上不起作用。 Neighb 是一个列表,我如何从该列表中构建一个不包含“bad_apple_Bad_apple”的列表?列表项是按数字选择的吗?

标签: python python-2.7 networkx


【解决方案1】:

我解决了:

if 'bad_apple_0' in Neighb: Neighb.remove('bad_apple_0')

谢谢!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多