2017-07-18 45 views
1

我相信我做了一個小錯誤概念,我找不到。基本上,我設計了一個簡單的數據容器來保存{key1:[values1],key2:[values2]}。用戶名單的列表

class Cells(object): 
    def __init__(self, **kwargs): 
     self.data = {} 

    def __data_len__(self): 
     """ Length of data[first key] list. """ 
     _ = 0 
     for key in self.data.keys(): 
      if self.data[key]: 
       _ = len(self.data[key]) 
       break 
     return _ 

    def subtract_lists(self, x, y): 
     return [item for item in x if item not in y] 

    def add(self, to_add): 
     """ Add columns if not exist """ 
     if not set(to_add.keys()).issubset(self.data.keys()):  # New key means adding 
      new_keys = self.subtract_lists(to_add.keys(), \ 
              self.data.keys())  # it to our dict 
      newdict = dict.fromkeys(new_keys, \ 
            [] * self.__data_len__()) 
      self.data.update(newdict) 

     [self.data[key].append(to_add.get(key, '')) for key in self.data.keys()] 
     print('* Updated data is: %s' % self.data) 

############################## 
# Now, tests...    # 
############################## 
if __name__ == '__main__': 
    cells = Cells() 
    cells.add({'one':1, 'two':2, 'three': 3}) 

期望的輸出是如:

Updated data is: {'one': [1], 'two': [2], 'three': [3]} 

但它輸出:

Updated data is: {'one': [1, 2, 3], 'two': [1, 2, 3], 'three': [1, 2, 3]} 

即加入的每一個值到每個鍵,這是令人沮喪的。一個錯誤的地方?

回答

2

問題是,您將newdict中的所有值分配爲相同的空列表。請參閱此處查看相關行爲的解釋:Python initializing a list of lists。該值只獲得一次評估,並且字典中的所有值都存儲相同的列表對象。

順便說一句,[] * n(任何n)仍然只是[]

改變這一行:

newdict = dict.fromkeys(new_keys, \ 
           [] * self.__data_len__()) 

這樣:

newdict = {key: [] for key in new_keys} 
+0

輝煌。非常感謝你! – pmus