为生成的图的节点赋予属性

Giving attributes to nodes of a generated graph

我是 Python 和 NetworkX 的新手,我正在尝试将字典中的属性赋予使用图形生成器创建的网络节点。这是我的示例代码:

g = nx.watts_strogatz_graph(5,4,0.1)

name_dict = {
  0: "Alice",
  1: "Bob",
  2: "Carl",
  3: "Diana",
  4: "Elain",
}

nx.set_node_attributes(g, name, name_dict)

但是我收到以下错误:

    nx.set_node_attributes(g, name, name_dict)
NameError: name 'name' is not defined

如何定义从字典中给出值的属性名称 ('name')?

NameError: name 'name' is not defined

您收到此错误是因为您没有名为 name.

的变量

让我们看看我通过谷歌搜索“networkx set_node_attributes”找到的 the documentation:

set_node_attributes(G, values, name=None)[source]

Sets node attributes from a given value or dictionary of values.

Warning

The call order of arguments values and name switched between v1.x & v2.x.

Parameters

G (NetworkX Graph)

values (scalar value, dict-like) – What the node attribute should be set to. If values is not a dictionary, then it is treated as a single attribute value that is then applied to every node in G. This means that if you provide a mutable object, like a list, updates to that object will be reflected in the node attribute for every node. The attribute name will be name.

If values is a dict or a dict of dict, it should be keyed by node to either an attribute value or a dict of attribute key/value pairs used to update the node’s attributes.

name (string (optional, default=None)) – Name of the node attribute to set if values is a scalar.

这告诉我们字典必须是传入的第二个参数,而不是你拥有的第三个参数。

它还告诉我们 name 参数是一个可选字符串。

综上所述,您可以通过执行以下操作来修复您的代码:

nx.set_node_attributes(g, name_dict)

现在将 运行,但省略了属性的名称。如果您希望属性的名称为 'name',那么您可以传递一个字符串作为第三个参数:

nx.set_node_attributes(g, name_dict, 'name')

TLDR;您需要修复参数的顺序,并通过用引号将 'name' 括起来使其成为字符串而不是变量。