我用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
),V1
和V2
是两个列表(G
节点的分区)。函数Switch(, , )
是我之前定义的另一个函数,它返回V1
和V2
的更新,还有整数C
。
我的目的是返回列表best1
,best2
和tempcut
的最小值。该函数返回tempcut
的正确值,但另一方面它返回 V1
和V2
的最后值,但不返回best1
和best2
。
答案 0 :(得分:1)
你应该复制你的清单。您正在通过引用更改它。查看official Python FAQ,Thread
尝试:
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