有两个列表变量:listA和listB。两个列表都存储了三个MyClass实例。 listA和listB之间的区别在于listB的实例将self.attrA设置为" myValue"。在脚本结束时,我循环遍历listA和listB以检查它们的实例self.id属性是否匹配。如果他们这样做,我想用相应的listB实例更新(覆盖)listA实例(因此listA实例都将self.myAttr设置为" myValue"。奇怪的是listA实例即使在 他们设定为平等:`
inst_A = inst_B
错误在哪里?
class MyClass(object):
def __init__(self, arg):
super(MyClass, self).__init__()
self.id=None
self.attrA=None
if 'id' in arg.keys():
self.id=arg['id']
if 'attrA' in arg.keys():
self.attrA=arg['attrA']
listA=[]
for i in range(3):
listA.append( MyClass({'id':i}))
listB=[]
for i in range(3):
listB.append( MyClass({'id':i, 'attrA':'myValue'}))
for inst_A in listA:
for inst_B in listB:
if inst_A.id==inst_B.id:
inst_A=inst_B
for inst_A in listA:
print inst_A.attrA
答案 0 :(得分:3)
你的for循环不会改变你的列表,它会改变你的迭代变量。
for inst_A in listA: # this creates a new name called inst_A which points
# to a value in listA
for inst_B in listB:
if inst_A.id == inst_B.id:
# this assignment changes the inst_A name to now point to inst_B
inst_A = inst_B
# At the bottom of the loop, inst_A is recycled, so the value it was
# assigned to (inst_B) is forgotten
尝试:
for i in range(len(listA)):
for inst_B in listB:
if listA[i].id == inst_B.id:
# almost the same as above, except here we're changing the value
# of the i-th entry in listA
listA[i] = inst_B