I have a MultiDiGraph
, in which there may exist multiple edges between nodes that are differentiated based on a key. Across the graph I have many keys and I'd like to iterate over them, performing a task for each key.
One way I could deal with this is to iterate over all edges, and store the keys in a set. Then I'll be able to iterate over the elements of that set:
import networkx as nx
G = nx.MultiDiGraph()
G.add_edge('a', 'b', 1)
G.add_edge('a', 'b', 2)
G.add_edge('b', 'c', 1)
G.add_edge('c', 'a', 3)
# Iterate over edges in the map and store the keys
keys = set(e[2] for e in G.edges_iter(keys=True))
# Now do something for each key
for key in keys:
pass # do something
But this seems awfully inefficient, as I'll ultimately be iterating over the edges of G
, and then again back over keys
.
I understand that I can make this more efficient by building my set along the way:
keys = set()
for e in G.edges_iter(keys=True):
key = e[2]
if key in keys:
continue
keys.add(key)
# do something
But I'm really hoping there's something special in networkx
I just haven't come across, or some idiom to make this neat. Any ideas?
答案 0 :(得分:1)
NetworkX将密钥存储在邻接结构中,因此访问它们的唯一方法是迭代数据
这似乎是最好的方式
# Iterate over edges in the map and store the keys
keys = set(e[2] for e in G.edges_iter(keys=True))
除非您在添加边缘时可以使用按键。您可以继承add_edge
方法,以便在添加密钥时将密钥存储在单独的数据结构中。