从文本文件中,我尝试将以下两个值附加一个值作为键。这是代码:
# this is a sample file. The output that I would like is ["apple","orange"]
lines = "This is apple. This is orange".split()
d = defaultdict(list)
d[("This", "is")] = list
for i, tokens in enumerate(lines):
if "This" == lines[i] and "is" == lines[i+1]:
d[(lines[i], lines[i+1])].append([lines[i+2]])
print d[("This", "is")]
但是我得到了如下所示的错误:
TypeError: `append() takes exactly one argument (0 given)` on `d[(lines[i], lines[i+1])].append([lines[i+2]])`
有人可以帮忙吗?
答案 0 :(得分:2)
以下行分配list
类型本身,而不是list
实例。
d[("This", "is")] = list
以上行应替换为:
d[("This", "is")] = list()
或
d[("This", "is")] = []
或该行可以完全删除,因为如果字典中没有匹配的键,defaultdict
将处理该情况。