提问人:marfin 提问时间:2/15/2023 更新时间:2/15/2023 访问量:73
我想将 append() 附加到嵌套列表中,但最终附加到我的所有列表中,为什么?
I want to append() to a nested list, but end up appending to all my lists, why?
问:
我有我的对象:
def NewShip(length, width, height):
frontLeft = [] #ship[5]
frontRight = [] #ship[6]
midLeft = [] #ship[7]
midRight = [] #ship[8]
backLeft = [] #ship[9]
backRight = [] #ship[10]
for i in range(88):
x = []*18
frontLeft.append(x)
frontRight.append(x)
midLeft.append(x)
midRight.append(x)
backLeft.append(x)
backRight.append(x)
return [length, width, height, [], dict(), frontLeft, frontRight, midLeft, midRight, backLeft, backRight]
在每个“frontLeft”等中,我想添加一个名为“容器”的列表,如下所示:
[id, 20, 2, cargo]
在每个“backRight”等的 88 个列表中,每个列表中的每个容器中都应该只有 18 个这样的容器。
这就是我尝试过的:
def loadContainerToShip(ship,container):
newWeight = container[4]
lightestArea = getLightestArea(ship) #returns the index of the lightest area
lightestStack = getLightestStack(ship[lightestArea]) #returns index of the lightest stack(list)
loaded = False
for i in range(len(ship[lightestArea][lightestStack])):
#here i want to insert the new container if the container "below" in the tack is heavier
oldWeight = getTotalWeightContainer(ship[lightestArea][lightestStack][i])
if oldWeight <= newWeight:
#insertContainerOnShip
ship[lightestArea][lightestStack].insert(i,container)
ship[3].append(container)
addContainerToDict(ship,container)
loaded = True
break
if not loaded:
print(ship[lightestArea][lightestStack])
ship[lightestArea][lightestStack].append(container)
ship[3].append(container)
addContainerToDict(ship,container)
当我这样做时,我将每个容器插入到 NewShip 减速中提到的所有 6 个列表中。 所以所有列表都是相同的,而且它不会将另一个容器添加到列表中,它会覆盖是吗?为什么以及如何修复
答: 暂无答案
评论
x
x
x = []*18
是对同一内部列表的 18 个引用的列表。