python - python中赋值意味着指向地址?

标签 python python-3.x

我正在使用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/

相关文章:

python - Opencv中分割字符的掩码

python:ValueError:关闭文件上的I/O操作

python - 连续时间输入函数的低通滤波器(在python中)的实现

c++ - 使用 waf 构建系统将程序与 Boost.Asio 链接

python - PyQt5中的Segmentation fault (core dumped)错误

python - 如何使用 Xlwings 和 Python 合并同一 Excel 工作簿中的所有工作表

python-3.x - 如何正确猜测LogLog图线性回归中的初始点?

python - swagger_py_codegen 类型错误

python - ElementTree不以UTF-8写入数据

eclipse - Python3 PyQt4 创建一个简单的 QCheckBox 并更改 bool 变量