Networkx 删除边属性的pythonic方法

Networkx 删除边属性的pythonic方法,networkx,Networkx,为了从networkx图形中删除属性,我有以下代码: for (n1,n2) in graph.edges(data=False): for att in att_list: graph[n1][n2].pop(att, None) 有没有更符合python的方法呢?如果你只想删除一些列表中的一些属性,比如说att\u list for n1, n2, d in graph.edges(data=True): for att in att_list:

为了从networkx图形中删除属性,我有以下代码:

for (n1,n2) in graph.edges(data=False):  
    for att in att_list:  
        graph[n1][n2].pop(att, None)  

有没有更符合python的方法呢?

如果你只想删除一些列表中的一些属性,比如说
att\u list

for n1, n2, d in graph.edges(data=True):
    for att in att_list:
        d.pop(att, None)
或者,如果
pop
返回了您不使用的内容,您可以将最后一行替换为
if att in d:del d[att]
。与您的代码相比,改进之处在于通过使用
data=True
我可以立即获得
d
,而不必在以后引用
graph[n1][n1]

有关如何从字典中删除多个键的信息,请参阅(这就是
d
)。从根本上说,一旦你有了
d
,你的问题就变成了这样

或者,如果要清除所有属性,请注意,如果我们设置
data=True
,则
graph.edges
也会返回包含属性的字典。清除这本字典

for (n1, n2, d) in graph.edges(data=True):
    d.clear()
这里有一个完整的例子

import networkx as nx
G=nx.Graph()
G.add_edge(1,2,weight=2)
G.edge[1][2]
> {'weight': 5}

for (n1, n2, d) in G.edges(data=True):
    d.clear()
G.edge[1][2]
> {}
#just to check the edge in the opposite order
G.edge[2][1]
> {}

在我们的例子中,我们只需要删除部分属性,而不是全部属性。