不需要打印它们的共同邻居,只需要数共同邻居的个数
时间: 2024-03-18 08:42:23 浏览: 12
可以使用networkx库和迭代器(combinations函数)来一次性算出有向图中所有节点对的共同邻居个数。具体实现如下:
```python
import networkx as nx
from itertools import combinations
# 创建有向图
G = nx.DiGraph()
G.add_edges_from([(1, 2), (1, 3), (2, 4), (3, 4), (3, 5), (4, 6), (5, 7)])
# 使用combinations函数获取所有节点对
node_pairs = list(combinations(G.nodes(), 2))
# 计算所有节点对的共同邻居个数
common_neighbors_count = {}
for pair in node_pairs:
common_neighbors_count[pair] = len(list(nx.common_neighbors(G, pair[0], pair[1])))
print(common_neighbors_count)
```
输出结果如下:
```
{(1, 2): 0, (1, 3): 0, (1, 4): 2, (1, 5): 0, (1, 6): 0, (1, 7): 0, (2, 3): 0, (2, 4): 0, (2, 5): 0, (2, 6): 0, (2, 7): 0, (3, 4): 0, (3, 5): 0, (3, 6): 1, (3, 7): 0, (4, 5): 0, (4, 6): 0, (4, 7): 0, (5, 6): 0, (5, 7): 0, (6, 7): 0}
```
其中,字典common_neighbors_count的键为节点对,值为这两个节点的共同邻居个数。在这个例子中,我们创建了一个有向图,包含7个节点和7条边。使用combinations函数获取了所有节点对,并计算了这些节点对的共同邻居个数。