python - 当我尝试分配给一个列表时,为什么每个列表值都会改变?
问题描述
我正在尝试使用背包问题进行简单的爬山。
我有一个调整函数,旨在返回输入它的二进制值列表的稍微修改的值。然后我将这个新值与现有值进行比较,看看哪个更好。
但是,我遇到了这个奇怪的问题,当我尝试将新解决方案分配为当前解决方案的调整副本时,当前解决方案和新解决方案都立即被调整后的值替换。循环中的每个列表都被替换为相同的值,我不知道为什么。我已经对其他具有相同效果的列表进行了同样的尝试。为什么会这样?
编辑:从数组更改为列表
from random import randrange
import numpy as np
val = [8, 7, 6, 3, 3]
iteration = 0
def generateInitialState():
array = []
k=0
while k != len(val):
array.append(randrange(0,2))
k+=1
return array
CurrentSolution = generateInitialState()
def Quality(Solution):
sum_items = 0
newValue = np.multiply(val,Solution)
for item in newValue:
sum_items += item
return sum_items
def Tweak(Solution):
print(str(Solution) + ' : ' + str(Quality(Solution)))
TempSolution = Solution
if Solution[iteration] is 0:
TempSolution[iteration] = 1
else:
TempSolution[iteration] = 0
print(str(TempSolution) + ' : ' + str(Quality(TempSolution)))
return TempSolution
while iteration < 5:
iteration+=1
NewSolution = Tweak(CurrentSolution)
if Quality(NewSolution) > Quality(CurrentSolution):
print('New good value detected'+ str(Quality(NewSolution)))
CurrentSolution = NewSolution
else:
print('Best solution found')
break
解决方案
TempSolution = Solution[:]
这解决了问题!更多细节在评论中
推荐阅读
- django - 从 expressjs 端点向 django 发送 post 请求
- css - 如何使用 angular 和 bulma 使导航栏汉堡菜单在 iPhone 等小屏幕上工作?
- python - python多处理初始化的开销比收益更糟糕
- sql - 用于排除的 SQL
- c# - 如何将 IQueryable/IEnumerable 结果转换为自定义模型 C# EntityFramework
- excel - 如何在所有子例程中使用宏变量
- php - 如何在 PHP 中将新记录添加到多维数组中?
- python - 从 Pandas 绘制某些数据点
- css - 填充网格容器,以便始终填充最后一个网格项区域
- javascript - Jquery 拖放项目计数和 Ajax 发布更新