将变量作为参数传递给networkx.add_edge()属性(Passing variables as arguments to networkx.add_edge() attributes)
我正在尝试在python中编写以下代码。
g = networkx.Digraph() g.add_edge(1,2,x = 2)这里的'x'是一个变量。 但是networkx似乎将此作为属性的名称。 我需要传递x内部的内容作为属性的名称。 我该怎么做?
I'm trying to write the following piece of code in python.
g = networkx.Digraph() g.add_edge(1,2,x = 2)The 'x' here is a variable. But networkx seems to take this as a name of the attribute. I need to pass what's inside x as the name of the attribute. How do I do it?
最满意答案
add_edge接受属性的dict 。 您只需要将属性/值对放在dict :
g.add_edge(1, 2, {x:2}) # or more explicitly g.add_edge(1, 2, attr_dict={x:2})例:
In [25]: g = networkx.DiGraph() In [26]: x = 'some string' In [27]: g.add_edge(1, 2, {x:2}) In [28]: g[1][2] Out[28]: {'some string': 2}add_edge takes a dict for attributes. You just need to put the attribute/value pairs in a dict:
g.add_edge(1, 2, {x:2}) # or more explicitly g.add_edge(1, 2, attr_dict={x:2})Example:
In [25]: g = networkx.DiGraph() In [26]: x = 'some string' In [27]: g.add_edge(1, 2, {x:2}) In [28]: g[1][2] Out[28]: {'some string': 2}更多推荐
发布评论