簡體   English   中英

在 NetworkX 圖中添加具有屬性的節點

[英]Adding a node with attribute in a NetworkX graph

networkx 教程暗示了添加具有屬性的節點的可能性。

如果您的容器產生形式為(node, node_attribute_dict) 2 元組,您還可以添加節點和節點屬性

當我用add_node方法嘗試它時,我得到一個 TypeError:

>>> import networkx as nx
>>> G = nx.Graph()
>>> G.add_node(('person1', {'name': 'John Doe', 'age': 40}))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/media/windows/Users/godidier/Projects/semlab/research/env/lib/python3.7/site-packages/networkx/classes/graph.py", line 506, in add_node
    if node_for_adding not in self._node:
TypeError: unhashable type: 'dict'

我錯過了什么? 還是只能使用add_nodes_from方法添加具有屬性的節點?

在你的情況下正確的方法是G.add_nodes_from

>>> G = nx.Graph()
>>> G.add_nodes_from([('person1', {'name': 'John Doe', 'age': 40})])
>>> G.nodes['person1']
{'name': 'John Doe', 'age': 40}

或者也直接使用add_node

>>> G = nx.Graph()
>>> G.add_node('person1', name='John Doe', age=40)
>>> G.nodes['person1']
{'name': 'John Doe', 'age': 40}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM