错误值的问题"在Python中返回" -ed(深拷贝问题)

时间:2014-11-01 10:26:49

标签: python deep-copy

我用Python定义了以下函数:

def step(G,V1,V2):
    tempcut=sys.maxint
    for k in range(min(len(V1),len(V2))):
        V1, V2, C=Switch(G,V1,V2,k)
        print(C)
        if C<tempcut:
           tempcut=C
           best1=V1
           best2=V2
           print('enter')
           print(tempcut)
           print(best1)  
           print(best2)      
    return best1, best2, tempcut,  

G是图表对象(networkx),V1V2是两个列表(G节点的分区)。函数Switch(, , )是我之前定义的另一个函数,它返回V1V2的更新,还有整数C

我的目的是返回列表best1best2tempcut的最小值。该函数返回tempcut的正确值,但另一方面它返回 V1V2的最后值,但不返回best1best2

2 个答案:

答案 0 :(得分:1)

你应该复制你的清单。您正在通过引用更改它。查看official Python FAQThread

尝试:

import copy

def step(G,V1,V2):
    tempcut=sys.maxint
    for k in range(min(len(V1),len(V2))):
        V1, V2, C=Switch(G,V1,V2,k)
        print(C)
        if C<tempcut:
           tempcut=C
           best1=copy.copy(V1) #or : best1= V1[:] as Serge suggested  
           best2=copy.copy(V2) #or : best2= V2[:] as Serge suggested  
           print('enter')
           print(tempcut)
           print(best1)  
           print(best2)      
    return best1, best2, tempcut, 

答案 1 :(得分:0)

更安全的构造可能会这样做:

import copy                                 # use copy as Taha proposed
def step( G, V1, V2 ):
    tempcut = sys.maxint
    best1   = []                            # init for a case if() would never come true
    best2   = []                            # init for a case if() would never come true
    for k in range( min( len( V1 ), len( V2 ) ) ):
        V1, V2, C = Switch( G, V1, V2, k )
        print( C )
        if C < tempcut:
           tempcut = C
           best1   = copy.copy( V1 )        # use copy as Taha proposed
           best2   = copy.copy( V2 )        # use copy as Taha proposed
           print( 'enter' )
           print( tempcut )
           print( best1 )
           print( best2 )
    return ( best1, best2, tempcut,  )      # return as tuple