python - 在 NetworkX 图中添加具有属性的节点

标签 python networkx

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/

相关文章:

python - 在 Python 中检查成员是否存在

python ,网络

python - 具有不同节点集的两个 NetworkX 图之间的差异

python - 在 NetworkX 中绘制图形

python - ornado.websocket 和 [Errno 24] 打开文件太多

python - 使用 WSGI 进行多进程

python - Networkx 和 nx.write_gexf ... 动态节点属性

Python NetworkX max_flow_min_cost 函数永远运行

Python插值数据列表列表

python - Sage 在排列元素上找不到cycle_type() 属性