Skip to content

Files

Latest commit

ae68a0c · Nov 20, 2019

History

History
62 lines (39 loc) · 1.21 KB

36.md

File metadata and controls

62 lines (39 loc) · 1.21 KB

Python 图

原文: https://pythonspot.com/python-graph/

介绍

数学和计算机科学中的图由节点组成,这些节点可以相互连接,也可以不相互连接。 节点之间的连接称为边。图可以是有向的(箭头)或无向的。 边可以表示距离或重量。

graph mathematics

默认图(左),有向图(右)

Python 没有图数据类型。 要使用图,我们可以使用模块,也可以自己实现:

  • 自己实现图

  • networkx模块

Python 中的图

有向图可以定义为:

#!/usr/bin/env python

graph = {'A': ['B', 'C'],
         'B': ['C', 'A'],
         'C': ['D'],
         'D': ['A']}

print(graph)

使用networkx的图

networkx软件模块支持创建,处理图。

#!/usr/bin/env python
import networkx as nx

G=nx.Graph()
G.add_node("A")
G.add_node("B")
G.add_node("C")
G.add_edge("A","B")
G.add_edge("B","C")
G.add_edge("C","A")

print("Nodes: " + str(G.nodes()))
print("Edges: " + str(G.edges()))

结果:

Nodes: [‘A’, ‘C’, ‘B’]
Edges: [(‘A’, ‘C’), (‘A’, ‘B’), (‘C’, ‘B’)]