开始使用免费开始使用

Specifying a weight on edges

Weights can be added to edges in a graph, typically indicating the "strength" of an edge. In NetworkX, the weight is indicated by the 'weight' key in the metadata dictionary.

Before attempting the exercise, use the IPython Shell to access the dictionary metadata of T and explore it, for instance by running the commands T.edges[1, 10] and then T.edges[10, 1]. Note how there's only one field, and now you're going to add another field, called 'weight'.

本练习是课程的一部分

Introduction to Network Analysis in Python

查看课程

练习说明

  • Set the 'weight' attribute of the edge between node 1 and 10 of T to be equal to 2. Refer to the following template to set an attribute of an edge: network_name.edges[node1, node2]['attribute'] = value. Here, the 'attribute' is 'weight'.
  • Set the weight of every edge involving node 293 to be equal to 1.1. To do this:
    • Using a for loop, iterate over all the edges of T, including the metadata.
    • If 293 is involved in the list of nodes [u, v]:
      • Set the weight of the edge between u and v to be 1.1.

交互式实操练习

通过完成这段示例代码来试试这个练习。

# Set the weight of the edge
____ = 2

# Iterate over all the edges (with metadata)
for u, v, d in ____:

    # Check if node 293 is involved
    if 293 in ____:

        # Set the weight to 1.1
        ____ = 1.1
编辑并运行代码