Python NetworkX:如何访问具有特定数据值的边

2024-04-19 10:19:05 发布

您现在位置:Python中文网/ 问答频道 /正文

对于键渗流模型,我想用NetworkX用grid_2d_graph(l,l)建立一个正方形晶格。这给了我一个大小为lxl的正方形晶格,每个边open。你知道吗

我的想法是,我想随机选择一条图的边,然后检查是否已经分配了边(1保留边的原样,0将它添加到要从图中删除的边列表中),如果还没有分配(边有'state' = -1),我想以特定的概率随机选择p,如果边是打开的(保持原样),或者是关闭的(将其放在要删除的边列表中)。你知道吗

因此,我将数据属性'state' = -1的所有边保存为一个列表,然后尝试随机访问该列表的一个条目,然后将属性'state'更改为某个值。但这似乎是不允许的。当我试图编辑状态时,收到以下错误:

File "bond-percolation.py", line 39, in <module>
    ed[10][2] = 1
TypeError: 'tuple' object does not support item assignment

所以我的问题是,如何随机选取一条边并有效地更改'state'的值?你知道吗

这是我的密码:

import numpy as np
import networkx as nx
import matplotlib.pyplot as plt
import random

#Width of the quadratic lattice
l = 30
#Create grid
G = nx.grid_2d_graph(l,l)
#Total number of edges in the lattice
n = 2 * l * (l-1)
m = 0
#Set probability if an edge is open
p = 0.17
#Create empty list to add closed edges later
ed = []
ld = []

for e in G.edges(data = 'state', default = -1):
    ed.append(e)

#Creating the lattice
while (m != n):
    i = np.random.randint(n-1)
    a = random.random()
    if (ed[i][2] == -1):
        if (a > p):
            ld.append(ed[i])
        else:
            ed[i][2] = 1    
        m = m + 1


#We need this so that the lattice is drawn vertically to the horizon
pos = dict( (l,l) for l in G.nodes() )

#Draw the lattice
nx.draw_networkx(G, pos = pos, with_labels = False, node_size = 0)

#Plot it on the screen
plt.axis('off')
plt.show()

Tags: theinposimport列表ifasplt
2条回答

重读你的错误,我不认为你的错误与随机挑选边缘有关。相反,您错误地尝试分配状态值。你知道吗

ed[10][2]返回整个边(可能是dict)。在运行ed[10][2]时包含输出会很有帮助。你知道吗

你不能给它赋值。你可能想做ed[10][2]['state'] = 1

我相信您可以使用edge selector简单地搜索它。你知道吗

没有内置的选择器(afaik),但是您可以创建一个helper函数来循环遍历边并返回列表。你知道吗

def filter_edges(value):
   edge_list = []
   for u,v,s in G.edges(data='state'):
      if s == value:
          edge_list.append((u,v))

   return edge_list

相关问题 更多 >