def mainCall(nodeGroup):
maxScore = -9999999
maxPart = []
tempPartition = []
tempScore = 0.0
for j in range(2, 1+nodes/2):
nodeGroup = chooseInitPartition(j, nodeGroup)
tempScore, tempPartition = runKL(edgeList, nodeGroup, rounds)
print 'temp score', tempScore
print 'temp part', tempPartition, "\n"
if(maxScore < tempScore):
maxScore = tempScore
maxPart = tempPartition
print "max score", maxScore
print "maxpart", maxPart, "\n"
print 'before ret max part', maxPart
return maxScore, maxPart
finalScore, finalPartition = mainCall(nodeGroup)
上面的代码有问题。在 for
循环结束之前一切似乎都很好,但在那之后不是在 print 'before ret max part'
行打印 maxPart
值,它打印 tempPartition
的最后一个值(两者都代表一个数字列表)。
打印语句确认每次都不满足 if
条件,尤其是循环中的最后几次运行。所以我看不到 tempPartition
的值是如何传输到 maxPart
的。请在这件事上给予我帮助。这让我发疯。我确定我错过了一些简单的东西。谢谢!
编辑:
为 runKL
添加代码
def runKL(edgeList, nodeGroup, rounds):
nodeSwap = [0]*nodes
maxLogLScore = 0.0
edgeListLen = len(edgeList)
networkPartitionStore = []
logLScores = []
#Reset count
count = 0
#Start main loop
for i in range(rounds):
#mark all vertices as unswapped
for j in range(len(nodeSwap)):
nodeSwap[j] = 0
while(count < 100):
#Choose one edge uniformly randomly
randNum = random.uniform(0,1)
edge = edgeList[int(math.floor(edgeListLen*randNum))]
node1 = int(edge[0]) - 1
node2 = int(edge[1]) - 1
if((nodeGroup[node1] == nodeGroup[node2]) or (nodeSwap[node1] == 1) or (nodeSwap[node2] == 1)):
count += 1
continue
else:
#swap groups among nodes
temp = nodeGroup[node1]
nodeGroup[node1] = nodeGroup[node2]
nodeGroup[node2] = temp
#mark vertices as swapped
nodeSwap[node1] = 1
nodeSwap[node2] = 1
#calculate likelihood
logLScore = logLikelihood(edgeList, nodeGroup)
logLScores.append(logLScore)
#store network
networkPartitionStore.append(nodeGroup)
#reset count value
count = 0
#end while loop
#Choose the index of the maximum likelihood score
maxLogLScore = max(logLScores)
index = logLScores.index(maxLogLScore)
#print 'max score', modularityScores[index]
#Choose the corresponding network partition i.e. the way the groups have been assigned to the nodes
nodeGroup = networkPartitionStore[index]
#Reset partition storage list and modularity scores
networkPartitionStore = []
logLScores = []
#Store initial network partition structure and modularity score.
networkPartitionStore.append(nodeGroup)
logLScores.append(maxLogLScore)
return maxLogLScore, nodeGroup
最佳答案
当你说
maxPart = tempPartition
您不是在创建 tempPartition
的副本,而是让 maxPart
也指向 tempPartition
指向的同一个列表。要真正制作副本,您可以使用这样的切片符号
maxPart[:] = tempPartition
或
maxPart = tempPartition[:]
maxPart[:] = tempPartition
和 maxPart = tempPartition[:]
的区别在于前者改变了 maxPart
并复制了所有从 tempPartition
到 maxPart
的值,后者创建一个新列表,其中包含 tempPartition
中所有数据的副本,并使 maxPart
指向新创建的列表。
关于python - 在 python 中返回了错误的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20019547/