我使用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 本身。 这也适用于边界节点。
答案 0 :(得分: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