将变量作为参数传递给networkx.add

编程入门 行业动态 更新时间:2024-10-28 10:25:19
变量作为参数传递给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}

更多推荐

本文发布于:2023-07-31 00:06:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1340279.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:变量   参数   add   networkx

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!