有两个列表变量: listA和listB。这两个列表都存储三个MyClass实例。listA和listB的区别在于,listB的实例将其self.attrA设置为"myValue“。在脚本的末尾,我循环遍历listA和listB,以检查它们的实例self.id属性是否匹配。如果需要,我希望用相应的listA实例来更新(覆盖) listB实例(因此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 发布于 2014-04-04 19:25:49
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_Bhttps://stackoverflow.com/questions/22870935
复制相似问题