python - 查找networkx中每对节点之间的边
问题描述
在这里,我试图做一个布尔值,如果一对大小为 3 的节点之间不存在边,则打印这对
所以,我想使用 G.adj 并且到目前为止我知道如何将它与大小为 2 的对一起使用,但在这里我没有得到正确的结果。
例子:
(2, 5, 9) -> 打印
(0, 7, 8) - > 不打印
%pylab inline
import warnings
warnings.filterwarnings("ignore")
import networkx as nx
n = 10
G = nx.Graph()
G.add_nodes_from(range(n))
G.add_edge(0, n-1)
G.add_edge(0, 5)
G.add_edge(1, 6)
G.add_edge(2, 7)
G.add_edge(3, 8)
G.add_edge(4, 9)
for i in range(n-1):
G.add_edge(i, i+1)
s = set(itertools.combinations(G.nodes, 3))
for i in s:
if i not in G.adj:
print(i)
解决方案
如果你看G.adj
:
AdjacencyView({0: {9: {}, 5: {}, 1: {}}, 1: {6: {}, 0: {}, 2: {}}, 2: {7: {}, 1: {}, 3: {}}, 3: {8: {}, 2: {}, 4: {}}, 4: {9: {}, 3: {}, 5: {}}, 5: {0: {}, 4: {}, 6: {}}, 6: {1: {}, 5: {}, 7: {}}, 7: {2: {}, 6: {}, 8: {}}, 8: {3: {}, 7: {}, 9: {}}, 9: {0: {}, 4: {}, 8: {}}})
这基本上是一个嵌套字典。(6,5,0)
因此,评估in 之类的东西G.adj
会返回False
,导致你的三元组被打印出来。您可以编写更详细的逻辑来查询G.adj
,例如:
adj = G.adj
for x,y,z in s:
if (adj[x].get(y), adj[x].get(z), adj[y].get(z)) == (None, None, None):
print((x,y,z))
或者,您可以通过邻接矩阵:
am = nx.adjacency_matrix(G).todense()
s = set(itertools.combinations(G.nodes, 3))
for x,y,z in s:
if (am[x,y], am[x,z], am[y,z]) == (0,0,0):
print((x,y,z))
推荐阅读
- magento-1.9 - 起订金额属性名称 > 包邮 > 销售 > 发货方式 > 配置 > 系统
- javascript - 将事件添加到添加的动态 DOM 按钮 - jQuery
- sql - spark sql:计算具有不同谓词的出现次数
- git - Visual Studio 代码资源管理器中缺少 GIT 状态
- c# - 如何将参数添加到我在 Xamarin 中定义的命令?
- java - Struts 错误自动将字符串转换为垃圾值
- pyspark - 在 pyspark 中的 SQL 中广播多个视图
- macros - 如何匹配宏中的方法?
- javascript - Angular ng build --prod 在对象中结合数组和字符串抛出错误
- angular - Angular 6 - 将字节数组转换为 .docx