【发布时间】:2016-01-25 10:34:49
【问题描述】:
我是 Python 和 NetworkX 的新手。我有一个正方形的规则图G 和NxN 节点(一个格)。这些节点通过dict 标记(参见下面的代码)。现在我希望 edgelist 返回每个边的 start 和 endpoint ,而不是通过引用节点坐标而是通过节点给定的标签。
例子:
N = 3
G=nx.grid_2d_graph(N,N)
labels = dict( ((i, j), i + (N-1-j) * N ) for i, j in G.nodes() )
#This gives nodes an attribute ID that is identical to their labels
for (i,j) in labels:
G.node[(i,j)] ['ID']= labels[(i,j)]
edgelist=G.edges() #This gives the list of all edges in the format (Start XY, End XY)
如果我使用N=3 运行它,我会得到:
In [14]: labels
Out[14]: {(0, 0): 6, (0, 1): 3, (0, 2): 0, (1, 0): 7, (1, 1): 4, (1, 2): 1, (2, 0): 8, (2, 1): 5, (2, 2): 2}
此方案将左上角的节点标记为0,将节点(N-1)th 放置在右下角。这就是我想要的。现在edgelist的问题:
In [15]: edgelist
Out [15]: [((0, 1), (0, 0)), ((0, 1), (1, 1)), ((0, 1), (0, 2)), ((1, 2), (1, 1)), ((1, 2), (0, 2)), ((1, 2), (2, 2)), ((0, 0), (1, 0)), ((2, 1), (2, 0)), ((2, 1), (1, 1)), ((2, 1), (2, 2)), ((1, 1), (1, 0)), ((2, 0), (1, 0))]
我试图用这些行来解决问题(灵感来自这里:Replace items in a list using a dictionary):
allKeys = {}
for subdict in (labels):
allKeys.update(subdict)
new_edgelist = [allKeys[edge] for edge in edgelist]
但我得到了这件美妙的事情,它启发了我的星期一:
TypeError: cannot convert dictionary update sequence element #0 to a sequence
总结,我希望能够将edgelist 列表的元素替换为labels 字典的值,这样,例如,来自((2,0),(1,0)) 的边缘(对应于节点 8 和 7) 返回(8,7)。 感激不尽!
【问题讨论】:
标签: list loops dictionary list-comprehension networkx