【问题标题】:NetworkX - path around a nodeNetworkX - 节点周围的路径
【发布时间】:2016-09-10 06:49:36
【问题描述】:

我使用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]))

这样我得到了所有在 center 周围循环的节点,除了 center 本身。 这也适用于边界节点。

【问题讨论】:

  • 这个概念在方格中是有意义的,但可能不适用于其他图形。你能告诉我们更多关于你为什么要找这个,以便我们给出适当的答案吗?
  • 我使用方格来生成用于 CFD 模拟的网格(所谓的块结构网格)。为了能够实现一些网格平滑算法(例如基于角度的平滑),我需要对这些节点的引用。我有自己的数据结构,但我想采用图表,因为那里已经有许多其他功能可用,我可以将它们应用到我的项目中。而且我想获得更多关于图表的知识:)

标签: python networkx


【解决方案1】:

我相信,在这种特定情况下,足以找出您的邻居有哪些共同邻居。

代码是:

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

【讨论】:

  • 这解决了我的问题。感谢您提供逻辑和代码。所以在我看来,NetworkX 中没有专门的功能可以做到这一点。
  • 你很高兴@Andy,我还没有运行代码,所以它可能需要一些更改才能正常运行
  • 我不得不稍微修改一下。 “if neighb in”这一行需要类似:“if G.neighbors(neighb) in”。在我分享之前需要重构我的代码;)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多