Networkx:在没有for循环的情况下更新图中所有节点的单个属性

Networkx: Update single attribute of all nodes within a graph without for loop

我有一些代码可以更新 graph 的属性:

import networkx as nx

def update_nodes(graph):
    values = dict.fromkeys(graph.nodes, True)
    nx.set_node_attributes(graph, name='test_attribute', values=values)
    print(f"graph.nodes.data(): {graph.nodes.data()}")
    return graph

def loop(graph):
    graph.graph['test_attribute'] = False
    print(f"graph.nodes.data(): {graph.nodes.data()}")
    print(f"graph.graph['test_attribute']: {graph.graph['test_attribute']}")
    for node in range(0, len(graph.nodes)):
        print(f"graph.nodes[node]['test_attribute']: {graph.nodes[node]['test_attribute']}")
    return graph

graph = nx.erdos_renyi_graph(n = 3, p = 0.1, seed = 5)
for i in range(0, 2):
    graph = update_nodes(graph)
    graph = loop(graph)

这不会更新节点属性,而是将更新作为一个单独的实体应用于图形。有什么方法可以批量更新整个节点集的单个属性,而无需在某个地方停留 for node in (range(0, len(graph.nodes)): graph.nodes[node]['test_attribute'] = <new_value>

编辑:我应该澄清一下,我对图表内容的这次迭代不满意的原因是,在第二个循环的 运行 之前,所有节点的初始值都需要重置在此之后,质疑属性的值并基于此遵循不同的逻辑路径。所以我希望避免对所有节点进行两次迭代,尽管这第一个循环的计算强度要​​小得多,而且希望是不必要的。

如果要将所有节点的属性设置为相同的值,可以使用graph.add_nodes_from(graph.nodes,attribute_name='attribute_value')

这会更新提供的属性(如果不存在则添加节点和属性)但会保留图中已有的任何其他节点属性和边。请参阅以下示例:

import networkx as nx

graph = nx.erdos_renyi_graph(n = 3, p = 0.1, seed = 5)

# setup some initial attributes
graph.nodes[0]['attr1'] = 'foo'
graph.nodes[1]['attr1'] = 'bar'
graph.nodes[2]['attr1'] = 'baz'

# make some attribute we want to change
for node in graph.nodes:
    graph.nodes[node]['attr_to_change'] = 'orig_value'

# View initial attribute values
print(graph.nodes(data=True))
# [(0, {'attr1': 'foo', 'attr_to_change': 'orig_value'}),
#  (1, {'attr1': 'bar', 'attr_to_change': 'orig_value'}),
#  (2, {'attr1': 'baz', 'attr_to_change': 'orig_value'})]

# change the value of the attr_to_change attribute for all
graph.add_nodes_from(graph.nodes,attr_to_change='new_value')

# View updated attribute value
print(graph.nodes(data=True))
# [(0, {'attr1': 'foo', 'attr_to_change': 'new_value'}),
#  (1, {'attr1': 'bar', 'attr_to_change': 'new_value'}),
#  (2, {'attr1': 'baz', 'attr_to_change': 'new_value'})]