2014-04-04 36 views
0

有两个列表变量:listA和listB。这两个列表都存储MyClass的三个实例。 listA和listB之间的区别在于listB的实例将self.attrA设置为“myValue”。在脚本的最后,我循环访问listA和listB以检查它们的实例self.id属性是否匹配。如果他们这样做,我想更新(覆盖)与相应的listB实例的listA实例(所以listA实例都有他们的self.myAttr设置为“myValue”。奇怪的listA实例保持不变,即使在 他们设置为相等:'Python:根据来自另一个列表变量的相同类实例更新一个列表变量中的类实例

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 

回答

3

您的循环没有变异列表,它的变异你的迭代变量。

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 
+0

其实我不认为这是完全正确的。如果您将inst_A = inst_B更改为inst_A.attrA = inst_B.attrA,则可以正常工作。我的想法是,你可以改变迭代变量的值,但不能完全替换它。 –

+0

您无法将列表传递给'范围'。将其更改为'range(len(listA))'。 – jpmc26

+0

@ jpmc26错字,修正。 – Seth

相关问题