以@Aric的答案为基础,您可以找到像这样的红色鱼:
red_fish = set(n for u,v,d in G.edges_iter(data=True) if d['color']=='red' for n in (u, v) if G.node[n]['label']=='fish')print(red_fish)# set([2])
编写单行代码以创建具有特定属性的节点列表或生成器非常简单(此处显示了生成器)
import networkx as nxG = nx.Graph()G.add_node(1, label='one')G.add_node(2, label='fish')G.add_node(3, label='two')G.add_node(4, label='fish')# method 1fish = (n for n in G if G.node[n]['label']=='fish')# method 2fish2 = (n for n,d in G.nodes(data=True) if d['label']=='fish')print(list(fish))print(list(fish2))G.add_edge(1,2,color='red')G.add_edge(2,3,color='blue')red = ((u,v) for u,v,d in G.edges(data=True) if d['color']=='red')print(list(red))
如果您的图形很大且固定的,并且想要进行快速查找,则可以对这样的属性制作“反向字典”,
labels = {}for n, d in G.nodes(data=True): l = d['label'] labels[l] = labels.get(l, []) labels[l].append(n)print labels


