Python 如何为字典中的列表赋值
抱歉,我已经搜索了这个,它看起来很简单,但我无法找到它。我正在尝试为我的dict中的列表赋值:Python 如何为字典中的列表赋值,python,list,dictionary,assign,Python,List,Dictionary,Assign,抱歉,我已经搜索了这个,它看起来很简单,但我无法找到它。我正在尝试为我的dict中的列表赋值: class Test(object): def __init__(self): self.test = { "color": ["", "", "", ""], "incandescence": ["", "", "", ""] } def setTest(self): key = "color"
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行:“str”对象不支持项分配#
为什么我不能为第0个元素指定一个字符串?这与:
test = ["", "", ""]
test[0] = "test"
print test
回答:
clearDict
def clearDict(self):
for key in self.test:
self.test[key] = ""
您正在将dictionary元素设置为空字符串。我想你想要的是:
def clearDict(self):
for key in self.test:
for l in self.test[key]:
self.test[key][l] = ""
因为在创建了
x
之后,您调用了clearDict
,它将x.test
更改为{“颜色”:“”,“白炽度”:“”}
因此,当随后调用
setTest
时,您正试图将字典中空字符串值的第一个元素设置为“TEST”
,这会失败,因为字符串是不可变的。问题在于您的clearDict方法中。。。您正在将self.test[key]的值设置为字符串
self.test[key] = ""
一旦你这样做了,你就不能用索引设置字符串的一部分。。。如果您更改了创建新列表的方法,您的运气会更好
self.test[key] = []
注意 另一方面,您可以这样初始化,而不是使用[0]符号来设置第0个元素:
def __init__(self):
self.test = { "color": [], "incandescence": [] }
然后简单地添加到列表中以添加项目
def set_test(self):
self.test["color"].append("TEST")
在不必确切知道列表中有多少元素的情况下获得相同的结果。您是否让它起作用了?谢谢。几乎每个人都发现了这个问题,这是一个愚蠢的问题。啊。。我猜是第一个人的功劳。