简体   繁体   English

networkx:通过循环访问具有多个节点属性的节点

[英]networkx: accessing nodes with multiple node attributes via loop

I have a graph which has nodes/edges.我有一个包含节点/边的图。 I assigned the nodes some attributes我为节点分配了一些属性

 [(1, {'node_rx_signal': 0}),
 (2, {'node_rx_signal': 0}),
 (3, {'node_rx_signal': 1}),
 (4, {'node_rx_signal': 0}),
 (5, {'node_rx_signal': 1}),
 (6, {'node_rx_signal': 0}),
 (7, {'node_rx_signal': 0}),
 (8, {'node_rx_signal': 0})]

eg its is to signify that some nodes have this attribute set to 0 while others don't.例如,它表示某些节点​​将此属性设置为 0,而其他节点则没有。 With the help of for loop with an If condition I want to carry out a task but I can not seem to access the nodes with 'node_rx_signal' == 1 .在带有 If 条件的 for 循环的帮助下,我想执行一项任务,但我似乎无法使用'node_rx_signal' == 1访问节点。

nx.set_node_attributes(T1,values=0,name='node_rx_signal')
T1.nodes[3]['node_rx_signal'] = 1
T1.nodes[5]['node_rx_signal'] = 1  

for n, data in T1:
    if T1[n][data]==1:
        print(T1.node)
        print([n for n in T1.neighbors(n)])
    else:
        pass

Something along these lines.沿着这些路线的东西。

Something along these lines I guess:我猜是这样的:

import networkx as nx

T1 = nx.Graph()
for i in range(1, 9):
    T1.add_node(i)

nx.set_node_attributes(T1, values=0, name='node_rx_signal')
nx.set_node_attributes(T1, values=0, name='node_visited')

T1.nodes[3]['node_rx_signal'] = 1
T1.nodes[5]['node_rx_signal'] = 1
T1.nodes[6]['node_visited'] = 1

for node, attr in T1.nodes(data=True):
    if attr['node_rx_signal'] == 1:
        print(node)
    if attr['node_visited'] == 1:
        print(node)

Prints:印刷:

3
5
6

so your question has already an answer, I really stress out that before posting you should always look by a google search!!所以你的问题已经有了答案,我真的强调在发布之前你应该总是通过谷歌搜索来查看!! looping through nodes and extract attributes in Networkx 循环遍历节点并在 Networkx 中提取属性

in your case, a for loop calling for the nodes() method will do the trick son't forget the data=True if you are working with the attributes:在您的情况下,如果您正在使用属性,则调用 nodes() 方法的 for 循环将执行该技巧,不要忘记 data=True :

for my_node in T1.nodes(data=True):
     if my_node["node_rx_signal"] == 1:
          print(my_node)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM