Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/303.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何在图形的边上指定/附加权重?_Python_Algorithm_Graph Theory_Networkx - Fatal编程技术网

Python 如何在图形的边上指定/附加权重?

Python 如何在图形的边上指定/附加权重?,python,algorithm,graph-theory,networkx,Python,Algorithm,Graph Theory,Networkx,我想附加相同或不同的权重和一堆边。但我在NetworkX中找不到任何用于此的函数。如果函数在Networkx中可用,那么它是什么,如果不是,那么建议我如何在python中使用边附加权重? 例如:如果我有一些没有边的边列表 edges=[(1,2),(1,4),(3,4),(4,2)] 然后,我希望对所有边附加相同的权重(1) 预期输出为:weighted_edges=[(1,2,1)、(1,4,1)、(3,4,1)、(4,2,1)]参见networkx的 在你的例子中 G.add_edges_

我想附加相同或不同的权重和一堆边。但我在NetworkX中找不到任何用于此的函数。如果函数在Networkx中可用,那么它是什么,如果不是,那么建议我如何在python中使用边附加权重? 例如:如果我有一些没有边的边列表

edges=[(1,2),(1,4),(3,4),(4,2)]
然后,我希望对所有边附加相同的权重(1)

预期输出为:
weighted_edges=[(1,2,1)、(1,4,1)、(3,4,1)、(4,2,1)]
参见networkx的

在你的例子中

G.add_edges_from(edges, weight=1)
添加默认权重为1的所有边。

请参见networkx的

在你的例子中

G.add_edges_from(edges, weight=1)

添加默认权重为1的所有边。

最简单的版本是使用
add\u weighted\u edges\u from

import networkx as nx
G=nx.Graph()
G.add_weighted_edges_from([(1,2,1),(1,4,1),(3,4,1),(4,2,1)])
G.edges(data=True)  #print out the edges with weight
>[(1, 2, {'weight': 1}),
 (1, 4, {'weight': 1}),
 (2, 4, {'weight': 1}),
 (3, 4, {'weight': 1})]
如果已经定义了
,则使用其权重创建边:

edges=[(1,2),(1,4),(3,4),(4,2)]
edges_with_weights=[(a,b,1) for (a,b) in edges]
H=nx.Graph()
H.add_weighted_edges_from(edges_with_weights)
H.edges(data=True)
> [(1, 2, {'weight': 1}),
(1, 4, {'weight': 1}),
(2, 4, {'weight': 1}),
(3, 4, {'weight': 1})]

最简单的版本是使用

import networkx as nx
G=nx.Graph()
G.add_weighted_edges_from([(1,2,1),(1,4,1),(3,4,1),(4,2,1)])
G.edges(data=True)  #print out the edges with weight
>[(1, 2, {'weight': 1}),
 (1, 4, {'weight': 1}),
 (2, 4, {'weight': 1}),
 (3, 4, {'weight': 1})]
如果已经定义了
,则使用其权重创建边:

edges=[(1,2),(1,4),(3,4),(4,2)]
edges_with_weights=[(a,b,1) for (a,b) in edges]
H=nx.Graph()
H.add_weighted_edges_from(edges_with_weights)
H.edges(data=True)
> [(1, 2, {'weight': 1}),
(1, 4, {'weight': 1}),
(2, 4, {'weight': 1}),
(3, 4, {'weight': 1})]

有没有理由不考虑将元组映射为整数?[(1,2)=1,(1,4)=1,(3,4)=1,(4,2)=1]您没有考虑将元组映射到整数有什么原因吗?[(1,2) = 1 , (1,4) = 1 , (3,4) = 1 , (4,2) = 1]