我在python中有一个关于字典的问题,在参考页面中:http://docs.python.org/tutorial/datastructures.html#dictionaries。
“您不能将列表用作键,因为可以修改列表 使用索引分配,切片分配或类似方法放置 append()和extend()。“
但附加python字典的值是什么意思?
# A simple program that keep track of the line number(s) a word appeared in the novel
myDictionary = {}
with open('novel.txt') as book:
lineNumber = 1
for line in book:
# cleaned is a helper function to clean up the line
for word in cleaned(line).split():
if word in myDictinoary:
myDictionary[word].append(lineNumber)
else:
myDiciontary[word]=[lineNumber]
lineNumber += 1
myDictionary[word].append(lineNumber)
时究竟发生了什么?在我看来,一个列表,我想确定,一个键的值可以列出(或者在这种情况下它是一个元组)? 什么样的数据类型可以用作值?当我想要密钥存储多个值时。
答案 0 :(得分:1)
myDictionary[word].append(lineNumber)
将append()
方法调用myDIctionary[word]
中存储的任何值。如果该值恰好是list
类型,那么它会向该list
附加一个值。
如果myDictionary[word]
中存储的值不列表,或实现append()
的其他序列类型,则在其上调用append()
将为{{ 1}}。
答案 1 :(得分:0)
任何对象都可以用作dict
中的值。包括list
。
答案 2 :(得分:0)
任何东西都可以是字典中的值,可以是否可以删除。有问题的行扩展了dict中的值,而不是dict本身