英文:
How to construct a graph using a list of tuples in python in networkX?
问题
我试图从存储在变量中的元组列表中创建一个图。我找到了使用元组列表创建图的方法G.add_edges_from(e)
,但问题是这不起作用,当我尝试例如打印图时,它返回None
。我感谢解决我的问题的答案。我使用以下代码创建图:
import networkx as nx
e = [(1,2),(1,3),(2,3)]
G = nx.Graph()
g1 = G.add_edges_from(e)
print(g1)
更新:
我测试了这段代码,但在尝试打印时仍然返回None:
e = [[(1,2),(1,3),(2,3)],[(10,20),(10,30),(20,30)]]
graph_list = []
for i in e:
graph_list.append(nx.Graph().add_edges_from(i))
print(graph_list[0].nodes)
英文:
I am trying to make a graph from a list of tuples stored in a variable. I found G.add_edges_from(e)
for making graph using list of tuples. but the problem is that this does not work and when i try to for example print the graph it returns None
. I appreciate answers that solve my problem. I use the code below to make the graph:
import networkx as nx
e = [(1,2),(1,3),(2,3)]
G = nx.Graph()
g1 = G.add_edges_from(e)
print(g1)
Update:
I testes this code but again give None when trying to print:
e = [[(1,2),(1,3),(2,3)],[(10,20),(10,30),(20,30)]]
graph_list = []
for i in e:
graph_list.append(nx.Graph().add_edges_from(i))
print(graph_list[0].nodes)
答案1
得分: 3
让我们分析一下,好吗?
你将边的列表赋值给了e,然后用G创建了一个图。
然而,你的问题是,你试图将g1分配给add_edges_from
方法返回的内容(这是None)。
你实际想要的是这样的:
import networkx as nx
e = [(1,2),(1,3),(2,3)]
G = nx.Graph()
G.add_edges_from(e)
print(G)
由于add_edges_from
方法返回None
,它是按预期工作的,你应该尝试打印你的原始图。希望这可以帮助你理清情况!
编辑:
如果你坚持只使用元组列表,你可以不使用变量。使用列表来存储图对象,将它们在循环中存储如下:
e = [[(1,2),(1,3),(2,3)],[(10,20),(10,30),(20,30)]]
graph_list = []
for i in e:
G = nx.Graph()
G.add_edges_from(i)
graph_list.append(G)
print(graph_list[0].nodes)
print(graph_list[1].nodes)
然后,你可以使用索引来获取你制作的每个特定图(它们将分别存储在列表中)。
或者,你可能想要开始将每个图倾倒到一个JSON文件中(在这里回答)。
这可以解决你的RAM问题。
英文:
Let's break it down shall we?
You assigned a list of edges in e, then you made a graph with G.
However, your issue is you're trying to assign g1 to what the method add_edges_from
returns (which is None).
What you actually want is something like this:
import networkx as nx
e = [(1,2),(1,3),(2,3)]
G = nx.Graph()
G.add_edges_from(e)
print(G)
Since the add_edges_from
method returns None
it is working as intended, you should try printing your original graph instead. I hope this helps and clarifies things for you!
Edit:
If you insist on just using the list of tuples, you can just do away with variables. Use lists to store graph objects instead, keep storing them in a loop as such:
e = [[(1,2),(1,3),(2,3)],[(10,20),(10,30),(20,30)]]
graph_list = []
for i in e:
G = nx.Graph()
G.add_edges_from(i)
graph_list.append(G)
print(graph_list[0].nodes)
print(graph_list[1].nodes)
Then you can use indices to get each specific graph you make (which would be stored separately in the list)
Or you might want to start dumping each graph in a json file ([answered here] (https://stackoverflow.com/questions/32133009/method-to-export-networkx-graph-to-json-graph-file))
Which can solve your RAM issue
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论