python networkx 在某些条件下删除节点和边

标签 python set conditional-statements networkx

在 python 库 networkx 中,我想删除具有某些属性的图形的节点和边。例如,假设我想删除节点度数 < 2 的所有节点和边。考虑以下伪代码:

vdict = g.degree_dict()         #dictionary of nodes and their degrees
g.remove_from_nodes(v in g s.t. vdict[v] < 2)

我见过一些使用集合论符号的语法,但由于我对 Python 还是个新手,所以我不知道如何使用它。我如何将其转换为有效的 Python 代码?

最佳答案

Graph.remove_nodes_from() 方法采用节点列表(实际上是容器)。所以你只需要创建一个满足你条件的列表。您可以使用 Python 的 list comprehension结构紧凑地创建要删除的节点列表。

In [1]: import networkx as nx

In [2]: G = nx.Graph()

In [3]: G.add_edge(1,2)

In [4]: G.add_edge(1,3)

In [5]: G.add_edge(1,4)

In [6]: G.add_edge(2,3)

In [7]: G.add_edge(2,4)

In [8]: G.degree()
Out[8]: {1: 3, 2: 3, 3: 2, 4: 2}

In [9]: remove = [node for node,degree in dict(G.degree()).items() if degree > 2]

In [10]: remove
Out[10]: [1, 2]

In [11]: G.nodes()
Out[11]: [1, 2, 3, 4]

In [12]: G.remove_nodes_from(remove)

In [13]: G.nodes()
Out[13]: [3, 4]

关于python networkx 在某些条件下删除节点和边,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18261587/

相关文章:

bash - 在 bash 脚本中使用 while 循环检查两个条件

python复合和/或如果条件

python - 从函数向 Pandas 数据框添加多列

python - 脚本在文件结束前终止读取

python - 我无法在 Linux 上安装 Anaconda

c++ - 如何定义另一个类数据成员上的 `std::set` 排序?

python - 如何快速将 pandas 数据框中的某些集合与一组联合起来

Python - 对每行的最后 10 个日期中的值进行分组

c++ - STL 集 : insert two million ordered numbers in the most efficient manner

python-3.x - 使用df索引范围的条件