[Python]利用利用python实现复杂网络的博弈(实现复杂网络的博弈(1))——Networkx
相关知识相关知识
Networkx入门入门
首先,我们先使用Constructor来构建一个新的图:
import networkx as nx
G = nx.Graph()
这个图里面并没有点,也没有边,我们可以采用如下的方式来添加点和边:
G.add_node(0)
G.add_nodes_from([1, 2, 3, 4, 5, 6, 7, 8])
G.add_edge(0,1)
G.add_edges_from([(0,3), (1,4), (1,2), (2,5), (3,6), (3,4), (4,7), (4,5), (5,8), (6,7), (7,8)])
在networkx里面,node可以是除了None之外的任意hashable类型,比如char,string甚至于function,xml等也可以成为node,
当然在这里我们仅仅演示一下最为常见的int。
对于点和边的添加,其实还有其他方式,比如
G.add_star([1, 2, 3])# equal to G.add_edges_from([(1,2), (1,3)])
G.add_path([1, 2, 3])# equal to G.add_edges_from([(1,2), (2,3)])
G.add_circle([1, 2, 3])# equal to G.add_edges_from([(1,2), (2,3), (3,1)])
点和边的移除,只需要将API中的add改为remove即可:
G.remove_node(0)
G.remove_nodes_from([1, 2])
G.remove_edge(0,1)
G.remove_edges_from([(0,3), (1,4)])
如果希望一口气移除全部,请使用G.clear()
Networkx的基本数据结构,节点和边的属性的基本数据结构,节点和边的属性
我们可以查看一下G的具体结构:
>>>print(G[0])
{1: {}, 3: {}}
>>>print(list(G[0]))
[1, 3] >>>print(G[0][1])
{}
>>>print(G.node)
[0, 1, 2, 3, 4, 5, 6, 7, 8] >>>print(G.node[0])
{}
我们可以发现,G[0]这个操作,会为我们返回一个词典,他的key值即为他的邻居,而value值为一个空的字典字典,这个字典,正
是这个边的属性值。Networkx的这种结构被称作”the dictionary of dictionaries of dictionaries“,因而,我们也可以得知G的迭
代操作:
>>>print([n for n in G])
[0, 1, 2, 3, 4, 5, 6, 7, 8] >>>print([nbr for nbr in G[0]])
[1, 3]
我们可也可以通过G[0][1]来访问这条边所具有的属性。如果我们希望访问点的属性,则需要使用node方法,下面是关于属性的
展示:
>>>G[0]['type'] = 'A' #you should use 'node' to access the attribute of nodes!
TypeError: 'AtlasView' object does not support item assignment
>>>G.node[0]['type'] = 'A'
>>>print(G.node[0])
{'type': 'A'}
>>>G[0][1]['weight'] = 0.1
>>>print(G[0])
{1: {'weight': 0.1}, 3: {}}
虽然修改节点属性需要额外调用node成员,但是判断点的存在性和统计点的个数时,可以直接使用G:
>>>10 in G
False
>>>len(G)
10
评论0