作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我希望遍历由 n 个节点组成的图 G。并为每个第 n 个节点打开其邻居的字典。找出哪个邻居具有最大的数字属性。至少可以有 100 个邻居。并返回每个节点及其最大邻居的列表,即
[node,biggestneighbor]
[node,biggestneighbor]
[node,biggestneighbor]
节点的属性数据如下所示:
G.node[0]
{'type': 'a', 'pos': [0.76, 0.11]}
我感兴趣的属性是
G.node[0]['pos'][0]
0.76
有人知道这是否存在吗?或者如果不是的话,起始逻辑看起来像是一个好的起点吗?或者更聪明的人有更好的主意吗?
def thebiggestneighbor(G,attribute,nodes=None):
if nodes is None:
node_set = G
else:
node_set = G.subgraph(nodes)
node=G.node
for u,nbrsdict in G.adjacency_iter():
if u not in node_set:
continue
for v,eattr in nbrsdict.items():
vattr=node[v].get(attribute,None)
# then something like this but for many nodes. probably better subtraction
# of all nodes from each other and which one yeilds the biggest numner
#
# if x.[vattra] > x.[vattrb] then
# a
# elif x.[vattra] < x.[vattrb] then
# b
yield (u,b)
最佳答案
我喜欢用正确的数据结构解决这样的问题:
#nodes = [ (att_n, [(att_n, n_idx).. ] ), ... ] where each node is known by its index
#in the outer list. Each node is represented with a tuple: att_n the numeric attribute,
#and a list of neighbors. Neighbors have their numeric attribute repeated
#eg. node 1 has neighbors 2, and 3. node 2 has neighbor 1 and 4, etc..:
nodes = [ (192, [ (102, 2), (555, 3)] ),
(102, [ (192, 1), (333, 4) ] ),
(555, [ (192, 1),] ), ...
]
#then to augment nodes so the big neighbor is visible:
nodesandbigneighbor=[ (att_n, neighbors, max(neighbors)) for att_n, neighbors in nodes]
此外,如果您保持邻居列表的排序顺序从低数值属性到高,那么您可以这样做:
nodesandbigneighbor=[ (att_n, neighbors, neighbors[-1]) for att_n, neighbors in nodes]
这会更快(以节点插入时间为代价),但是您可以在插入时有效地解决问题。
关于python - 返回节点邻域中最大的节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10081149/
我是一名优秀的程序员,十分优秀!