简体   繁体   English

向图边添加随机属性

[英]Adding randomized attributes to graph edges

I've tried to add, randomly, one of two values of attribute in a dict, to each edge of some listed graphs, through the following code:我尝试通过以下代码将字典中的两个属性值之一随机添加到某些列出的图形的每个边缘:

import networkx as nx
import random

Glist = []

for _ in range(12):
    g = nx.erdos_renyi_graph(n = 20, p = random.random())
    Glist.append(g)

for i in range(len(Glist)):
    for u, v in Glist[i].edges():
        attribs = {Glist[i].edges(): {'relation': random.choice(['friend', 'enemy'])}}

def set_Net_att(my_list, my_dict):
    for _ in my_list:
        for i in range(len(my_list)):
            gatt = nx.set_edge_attributes(my_list[i], my_dict)

set_Net_att(Glist, attribs)

print(Glist[2].edges(data = True))

But I got this error:但我得到了这个错误:

TypeError                                 Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_14600/893381260.py in <module>
     14 for i in range(len(Glist)):
     15     for u, v in Glist[i].edges():
---> 16         attribs = {Glist[i].edges(): {'relation': random.choice(['friend', 'enemy'])}}
     17 
     18 def set_Net_att(my_list, my_dict):

TypeError: unhashable type: 'EdgeView'

How can I get things done?我怎样才能把事情做好? I'd really appreciate your support.我真的很感谢你的支持。

You do not construct the dictionary for the function set_edge_attributes correctly (and, in general, use too many non-Pythonic features in your code).您没有正确构建 function set_edge_attributes的字典(并且通常在代码中使用太多非 Pythonic 功能)。 Here is a correct (and improved) solution:这是一个正确(和改进)的解决方案:

# Build a list of graphs
glist = [nx.erdos_renyi_graph(n = 20, p = random.random()) for _ in range(12)]

# Generate and assign attributes
for g in glist:
    attribs = {edge: random.choice(['friend', 'enemy']) for edge in g.edges}
    nx.set_edge_attributes(g, attribs, "relation")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM