我正在使用python 3.6实现一个层次聚类算法(具有相似性),以下操作基本上是构建新的空图,并继续递归地连接原始相似度最大的组(由此处的列表表示)
代码位置1的代码,我想返回最佳分区,但是函数返回与comminity_list
完全相同,它看起来像best_partition = comminity_list。
让 best_partition
指向“comminity_list”的地址这是怎么发生的,我在这里出了什么问题?我应该如何解决这个问题?
def pearson_clustering(G):
H = nx.create_empty_copy(G). # build a empty copy of G(no vetices)
best = 0 #for current modularity
current =0 #for best modualarty
A = nx.adj_matrix(G). #get adjacent matrix
org_deg =deg_dict(A, G.nodes()) # degree of G
org_E = G.number_of_edges(). # number of edges of G
comminity_list = intial_commnity_list(G) # function return a list of lists here
best_partition = None
p_table =pearson_table(G) #pearson_table return a dictionary of each pair Pearson correlation
l = len(comminity_list)
while True:
if(l == 2): break
current = modualratiry(H,org_deg,org_E) #find current modularity
l = len(comminity_list)
p_build_cluster(p_table,H,G,comminity_list) #building clustering on H
if(best < current):
best_partition = comminity_list. #postion1
best = current #find the clustering with largest modularity
return best_partition #postion2
最佳答案
it looks like best_partition = comminity_list. make best_partition point to the address of 'comminity_list' how come it happens, what I got wrong here? how should I fix that ?
这只是 python 的隐式赋值行为。当您执行“best_partition = comminity_list”时,您只需将comminity_list分配给与best_partition相同的地址。
如果您想显式复制列表,您可以使用它(用comminity_list替换列表best_partition):
best_partition[:] = comminity_list
或copy function 。如果comminity_list有子列表,您将需要来自同一模块的deepcopy函数(否则您将获得原始列表的副本,但子列表仍然只是地址引用)。
best_partition = comminity_list.copy
关于python - python中赋值意味着指向地址?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53526176/