2014-04-04 33 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

相關問題