networkx tutorial提示添加具有属性的节点的可能性。
You can also add nodes along with node attributes if your container yields 2-tuples of the form
(node, node_attribute_dict)
当我尝试使用 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}
关于python - 在 NetworkX 图中添加具有属性的节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64841083/