如何在python networkx MultiDiGraph中检索或遍历边缘键 [英] How to retrieve or iterate over edge keys in python networkx MultiDiGraph

查看:608
本文介绍了如何在python networkx MultiDiGraph中检索或遍历边缘键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个MultiDiGraph,其中基于密钥进行区分的节点之间可能存在多个边缘.在整个图中,我有很多键,并且我想遍历它们,为每个键执行一个任务.

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

但这似乎效率很低,因为我最终将遍历G的边缘,然后再次遍历keys.

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

但是我真的很希望networkx中有一些特别的东西,我只是没碰过,或者有一些成语来使它整​​洁.有什么想法吗?

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?

推荐答案

NetworkX将密钥存储在邻接结构中,因此访问它们的唯一方法是对数据进行迭代

NetworkX stores the keys in the adjacency structure so the only way to access them is by iterating over data

这似乎是最好的方法

# Iterate over edges in the map and store the keys
keys = set(e[2] for e in G.edges_iter(keys=True))

除非您在添加边缘时可以使用关键点.您可以将add_edge方法子类化,以便在添加密钥时将其存储在单独的数据结构中.

unless you can the keys as you add the edges. You could subclass the add_edge method to store the keys in an separate data structure as you add them.

这篇关于如何在python networkx MultiDiGraph中检索或遍历边缘键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆