<p>创建许多边或节点属性时,可以指定这些属性。由你决定他们的名字</p>
<pre><code>import networkx as nx
G=nx.Graph()
G.add_edge(1,2,weight=5) #G now has nodes 1 and 2 with an edge
G.edges()
#[(1, 2)]
G.get_edge_data(2,1) #note standard graphs don't care about order
#{'weight': 5}
G.get_edge_data(2,1)['weight']
#5
G.add_node('extranode',color='yellow', age = 17, qwerty='dvorak', asdfasdf='lkjhlkjh') #nodes are now 1, 2, and 'extranode'
G.node['extranode']
{'age': 17, 'color': 'yellow', 'qwerty': 'dvorak', 'asdfasdf': 'lkjhlkjh'}
G.node['extranode']['qwerty']
#'dvorak'
</code></pre>
<p>或者,您可以使用dict来使用<code>nx.set_node_attributes</code>定义某些属性,并为使用<code>nx.get_node_attributes</code>定义特定属性的所有节点创建dict</p>
<pre><code>tmpdict = {1:'green', 2:'blue'}
nx.set_node_attributes(G,'color', tmpdict)
colorDict = nx.get_node_attributes(G,'color')
colorDict
#{1: 'green', 2: 'blue', 'extranode': 'yellow'}
colorDict[2]
#'blue'
</code></pre>
<p>类似地,还有<code>nx.get_edge_attributes</code>和<code>nx.set_edge_attributes</code></p>
<p>更多信息请参见networkx教程中的<a href="https://networkx.github.io/documentation/latest/tutorial/tutorial.html" rel="nofollow">here</a>。大约在本页的一半,标题为“节点属性”和“边缘属性”。有关<code>set...attributes</code>和<code>get...attributes</code>的具体文档可以在<a href="https://networkx.github.io/documentation/latest/reference/functions.html" rel="nofollow">here</a>的“属性”下找到</p>