I want to sample three edge attributes from a directed graph I built with networkX. The edges in the graph with the attribute 'dependency' are listed below:
import networkx as nx
import random
from random import choice
G=nx.DiGraph()
G.add_edge('x','a', dependency=0.4)
G.add_edge('x','b', dependency=0.6)
G.add_edge('a','c', dependency=1)
G.add_edge('b','c', dependency=0.3)
G.add_edge('b','d', dependency=0.7)
G.add_edge('d','e', dependency=1)
G.add_edge('c','y', dependency=1)
G.add_edge('e','y', dependency=1)
Now I want to sample three different edge attributes from above and multiply them with a random number between 0 and 1. It should look somehow like this:
for i in range(3):
sampled_edge = random.sample(G.edges, 1)
sampled_edge_with_random_number = sampled_edge['dependency'] * random.uniform(0,1)
print(sampled_edge_with_random_number)
But I keep getting the following error message:
TypeError: list indices must be integers or slices, not str
What is the best way to do this?
There were two mistakes in your script.
random.sample(G.edges, 1)
? Definitely it's list that contains one item therefore it can't be a key for any edge. Correct key is sampled_edge[0]
sampled_edge
? If it's list or tuple, it can't have any keys. The only thing that should have a key is EdgeView of your graph. It should be G.edges
then. After you identify some edge, you can access its atributes too. So just replace your sampled_edge['dependency']
with G.edges[sampled_edge[0]]['dependency']
in your script and that's it.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.