pythonic way to delete edge attributes

旧巷老猫 提交于 2021-01-27 17:50:35

问题


In order to remove attributes from a networkx graph I have the following code:

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

Is there a more pythonic way to do so?


回答1:


If you only want to delete a few attributes in some list, say att_list

for n1, n2, d in graph.edges(data=True):
    for att in att_list:
        d.pop(att, None)

Or you can replace the last line with if att in d: del d[att] if it bothers you that pop returns something that you aren't using. The improvement compared to your code is that by having data=True I get d immediately, rather than having to reference graph[n1][n1] later.

See Removing multiple keys from a dictionary safely for how to remove multiple keys from a dictionary (which is what d is). Fundamentally that's what your problem reduces to once you've got d.

Alternately, if you want to clear all of the attributes, then note that if we set data=True, then graph.edges also returns a dictionary with the attributes. Clear this dictionary.

for (n1, n2, d) in graph.edges(data=True):
    d.clear()

Here's a complete example

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]
> {}


来源:https://stackoverflow.com/questions/50314296/pythonic-way-to-delete-edge-attributes

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!