networkx包学习

1.创建图

创建一个没有结点也没有边的空图
结点可以是任意hash对象,字符串、图像、

import networkx as nx
G = nx.Graph()

2.添加图的结点

    def test_node(self):
        G = nx.Graph()
		
		#add_node()添加一个结点
        G.add_node(1)
        print(G.nodes)
		
		#add_nodes_from()添加多个结点
        G.add_nodes_from([2, 3])
        print(G.nodes)
        G.add_nodes_from([
            (4, {
   "color": "red"}),
            (5, {
   "color": "green"}),
        ])
        print(G.nodes)
        print(G.nodes.data())
        
        #将一个图中的结点合并到另一个图中
        H = nx.path_graph(10)
        G.add_nodes_from(H)
        print(G.nodes)
        print(G.nodes.data())

输出结果

[1]
[1, 2, 3]
[1, 2, 3, 4, 5]
[(1, {
   }), (2, {
   }), (3, {
   }), (4, {
   'color': 'red'}), (5, {
   'color': 'green'})]
[1, 2, 3, 4, 5, 0, 6, 7, 8, 9]
[(1, {
   }), (2, {
   }), (3, {
   }), (4, {
   'color': 'red'}), (5, {
   'color': 'green'}), (0, {
   }), (6, {
   }), (7, {
   }), (8, {
   }), (9, {
   })]
[1, 2, 3, 4, 5, 0, 6, 7, 8, 9, <networkx.classes.graph.Graph object at 0x0000028B528B66A0>]
[(1, {
   }), (2, {
   }), (3, {
   }), (4, {
   'color': 'red'}), (5, {
   'color': 'green'}), (0, {
   }), (6, {
   }), (7, {
   }), (8, {
   }), (9, {
   }), (<networkx.classes.graph.Graph object at 0x0000028B528B66A0>, {
   })]

3.添加图的边

    def test_edge(self):
        G = nx.Graph()

        #add_edge()添加一条边
        G.add_edge(1, 2)
        e = (2, 3)
        G.add_edge(*e)
        print(G.edges)
        print(G.edges.data())

        #添加边列表
        G.add_edges_from([(1, 2), (1, 3)])
        print(G.edges)
        print(G.edges.data())

        H = nx.path_graph(10)
        print(H.edges)
        G.add_edges_from(H.edges
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值