【问题标题】:Adding a node with attribute in a NetworkX graph在 NetworkX 图中添加具有属性的节点
【发布时间】:2020-11-15 04:01:18
【问题描述】:

networkx tutorial 暗示了添加具有属性的节点的可能性。

如果您的容器产生(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 方法添加具有属性的节点?

【问题讨论】:

    标签: python networkx


    【解决方案1】:

    在您的情况下,正确的方法是 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}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-04-12
      • 1970-01-01
      • 1970-01-01
      • 2023-02-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多