Subgraphs II
In the previous exercise, we gave you a list of nodes whose neighbors we asked you to extract.
Let's try one more exercise in which you extract nodes that have a particular metadata property and their neighbors. This should hark back to what you've learned about using list comprehensions to find nodes. The exercise will also build your capacity to compose functions that you've already written before.
本练习是课程的一部分
Introduction to Network Analysis in Python
练习说明
- Using a list comprehension, extract nodes that have the metadata
'occupation'as'celebrity'alongside their neighbors:- The output expression of the list comprehension is
n, and there are two iterator variables:nandd. The iterable is the list of nodes ofT(including the metadata, which you can specify usingdata=True) and the conditional expression is if the'occupation'key of the metadata dictionarydequals'celebrity'.
- The output expression of the list comprehension is
- Place them in a new subgraph called
T_sub. To do this:- Iterate over the nodes, compute the neighbors of each node, and add them to the set of nodes
nodesetby using the.union()method. This last part has been done for you. - Use
nodesetalong with theT.subgraph()method to calculateT_sub.
- Iterate over the nodes, compute the neighbors of each node, and add them to the set of nodes
- Draw
T_subto the screen.
交互式实操练习
通过完成这段示例代码来试试这个练习。
# Extract the nodes of interest: nodes
nodes = [n for n, d in ____ if ____ == ____]
# Create the set of nodes: nodeset
nodeset = set(nodes)
# Iterate over nodes
for n in ____:
# Compute the neighbors of n: nbrs
nbrs = ____
# Compute the union of nodeset and nbrs: nodeset
nodeset = nodeset.union(nbrs)
# Compute the subgraph using nodeset: T_sub
T_sub = ____
# Draw T_sub to the screen
____
plt.show()