2016-02-19 58 views
1

對不起,我搜索了這個,它似乎很簡單,但我無法弄清楚。我想在我的字典值賦給一個列表:如何分配到字典中的列表

class Test(object): 
    def __init__(self): 

     self.test = { "color": ["", "", "", ""], 
          "incandescence": ["", "", "", ""] } 

    def setTest(self): 
     key = "color" 
     print "KEY is", key 
     self.test[key][0] = "TEST" 

     print self.test 

    def clearDict(self): 
     for key in self.test: 
      self.test[key] = ""  

x = Test() 
x.clearDict() 
x.setTest() 

錯誤:第1行:類型錯誤:文件行10:「海峽」對象不支持項目分配#

爲什麼我不能爲第0個元素分配一個字符串?這是怎麼不一樣:

test = ["", "", ""] 

test[0] = "test" 

print test 

回答: '測試', '', '']

+0

你有沒有得到它的工作? – timgeb

回答

1

clearDict

def clearDict(self): 
    for key in self.test: 
     self.test[key] = "" 

要設置字典元素是一個空白字符串。我想你想要的東西,如:

def clearDict(self): 
    for key in self.test: 
     for l in self.test[key]: 
      self.test[key][l] = "" 
+0

謝謝。每個人都發現了這個問題,這是一個愚蠢的問題。呃..給我猜的第一個人的功勞。 – Zak44

1

好,因爲創建x後調用clearDict它而改變x.test{"color": '', "incandescence": ''}

所以調用setTest當事後你試圖設置爲空字符串的第一個元素您的字典中的值爲"TEST",因爲字符串不可變而失敗。

1

的問題是在你的clearDict方法......你的self.test [關鍵]的值設置爲一個字符串

self.test[key] = "" 

一旦你這樣做,你不能設置一個字符串的一部分一個索引...如果你改變你的方法來創建一個新的列表,你將會有更好的運氣。

self.test[key] = [] 

注意

順便說一句,而不是使用[0]符號設置第0個元素,你可能會初始化像這樣:

def __init__(self): 
    self.test = { "color": [], "incandescence": [] } 

然後只需附加到您的清單添加項目

def set_test(self): 
    self.test["color"].append("TEST") 

以實現相同的結果,而不必確切地知道列表中有多少元素。

相關問題