繁体   English   中英

NetworkX - 节点周围的路径

[英]NetworkX - path around a node

我使用NetworkX创建以下图表。

Networkx图

使用以下代码创建图表:

G = nx.grid_2d_graph(4,3)

之后,关于它们的位置修改了两个节点(仅用于解释图,对于答案不是必需的)。

使用以下代码:

G.neighbors((1, 1))

输出:

[(0, 1), (1, 2), (1, 0), (2, 1)]

我需要的还有以下几点:

[(0, 2), (2, 2), (2, 0), (0, 0)]

这将构成围绕(1,1)的“循环”,其包含该“循环”中的所有节点。 由于我不知道图表方面的正确命名,因此我很难在我正在寻找的内容之后进行搜索。

编辑:

在受到@orestiss的启发和摆弄后,我想出了这个。

l = list()
center = (1, 1)
for neighb in G.neighbors(center):
    others = [n for n in G.neighbors(center) if n != neighb]
    for other in others:
        l.append([n for n in nx.common_neighbors(G, neighb, other) if n != center])
    l.append([neighb])
lf = list(set([item for sublist in l for item in sublist]))

有了这个,我得到了围绕中心的所有节点,除了中心本身。 这也适用于边界节点。

我相信在这个特定情况下,足以找到你的邻居有哪些共同点。

代码将是:

in_loop = set()
root = (1,1)

for neighb in G.neighbors(root):
    others = [n for n in G.neighbors((1,1)) if n != neighb]
    for other in others:
         if neighb in [x for x in G.neighbors(other) if x != root]:
              in_loop.add(neighb)
              break

print in_loop

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM