gpt4 book ai didi

python - networkx代码python的解释

转载 作者:行者123 更新时间:2023-12-01 06:01:52 25 4
gpt4 key购买 nike

我是Python编码新手。我希望修改此代码以开发二分两种模式版本。它是来自networkx的代码,用于制作几何随机图。我已经掌握了这个函数的大部分内容,但我很难理解第 94 行到第 99 行到底在做什么。我理解 while、zip 和nodes.pop(),但其他部分对于新手来说是令人困惑的。任何人都可以帮助解释一下这部分代码的作用比给出的一般描述更多吗?

G=nx.Graph()
G.name="Random Geometric Graph"
G.add_nodes_from(range(n))
if pos is None:
# random positions
for n in G:
G.node[n]['pos']=[random.random() for i in range(0,dim)]
else:
nx.set_node_attributes(G,'pos',pos)
# connect nodes within "radius" of each other
# n^2 algorithm, could use a k-d tree implementation
nodes = G.nodes(data=True)
while nodes: #line94
u,du = nodes.pop()
pu = du['pos']
for v,dv in nodes:
pv = dv['pos']
d = sum(((a-b)**2 for a,b in zip(pu,pv))) #line99
if d <= radius**2:
G.add_edge(u,v)
return G

最佳答案

nodes = [some list]
while nodes:
a = nodes.pop()
for b in nodes:
# do something

这段代码是一个非常常见的习惯用法,它将每个节点与其他每个节点恰好组合一次(因此 ab 的顺序对于执行的操作并不重要在 # do something 部分)。

它之所以有效,是因为在while的条件下空列表被认为是假值。循环,而非空列表被视为 bool true。

d = sum(((a-b)**2 for a,b in zip(pu,pv)))

该行计算 Euclidean distance 的平方两个向量的pupv 。通过拆解可以最好地证明这一点:

>>> pu = (6,6,6)
>>> pv = (1,3,7)
>>> zip(pu, pv)
[(6, 1), (6, 3), (6, 7)]
>>> [(a-b) for a,b in zip(pu, pv)]
[5, 3, -1]
>>> [(a-b)**2 for a,b in zip(pu, pv)]
[25, 9, 1]
>>> sum((a-b)**2 for a,b in zip(pu, pv))
35

在最后一步中,我们不再使用列表理解,因为我们不需要列表。 sum只需要某种可迭代形式的值,因此我们使用生成器表达式。

关于python - networkx代码python的解释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10042181/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com