python中的引用标识符

2024-04-16 07:27:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这样的代码(为了简单起见,它被缩减了,所以不要关注内容):

for x in range(1,4):
    print(x)
    print(vLast)

    #1st level
    for the_key,the_value in graph.items():
        numerator=0
        denominator=0
        result=0

        #2nd level
        for the_key2,the_value2 in graph[the_key].items():
            numerator = 0
            denominator = 5
            numerator = the_value2

            result = numerator/denominator

        result = alpha*result+(1-alpha)/len(vLast)
        print(vLast['p2p']) #Line A
        vCurrent[the_key] = result #Line B
        print(vLast['p2p'])
    vLast=vCurrent #Line C
    x=x+1

x = 2执行Line B后,vLast['p2p']result变量的值。你知道吗

我知道这与引用标识符有关,但我不想在执行Line C之前更改值,否则第一级'for'循环在退出之前使用不同的vLast['p2p']

换句话说,如何在执行Line C之前不更改vLast的值?你知道吗

以下是x = 2处的上述打印输出

    2
    {'p2p': 0.17517241379310347, 'nnn': 0.3451724137931035, 'ppp': 0.3451724137931035, 'fff': 0.3451724137931035}
    0.17517241379310347 
    0.20750000000000002 
...

(我预计最后一行为0.17517241379310347,而不是0.20750000000000002)


Tags: thekeyinforlineitemsp2presult
1条回答
网友
1楼 · 发布于 2024-04-16 07:27:50

你需要用浅拷贝

vLast = vCurrent.copy() #Line C

这将把vCurrent内容复制到vLast,但是这两个对象不会被绑定。同样的方法也适用于列表。你知道吗

相关问题 更多 >