Select network nodes with a given attribute value

混江龙づ霸主 提交于 2020-11-30 06:22:20

问题


I'd like to select and perform operations on nodes within a graph with particular attributes. How would you select nodes with a given attribute value? For example:

P=nx.Graph()
P.add_node('node1',at=5)
P.add_node('node2',at=5)
P.add_node('node3',at=6)

Is there a way to select only the nodes with at == 5?.

I'm imagining something like (this doesn't work):

for p in P.nodes():
    P.node[p]['at'==5]

回答1:


Python <= 2.7:

According to the documentation try:

nodesAt5 = filter(lambda (n, d): d['at'] == 5, P.nodes(data=True))

or like your approach

nodesAt5 = []
for (p, d) in P.nodes(data=True):
    if d['at'] == 5:
        nodesAt5.append(p)

Python 2.7 and 3:

nodesAt5 = [x for x,y in P.nodes(data=True) if y['at']==5]



回答2:


Sample code if someone is stuck

import networkx as nx

P=nx.Graph()
P.add_node('node1',at=5)
P.add_node('node2',at=5)
P.add_node('node3',at=6)

# You can select like this
selected_data = dict( (n,d['at']) for n,d in P.nodes().items() if d['at'] == 5)
# Then do what you want to do with selected_data
print(f'Node found : {len (selected_data)} : {selected_data}')


来源:https://stackoverflow.com/questions/31922917/select-network-nodes-with-a-given-attribute-value

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!