输入:
Once upon a time a time this upon a
输出:
代码:
def countTuples(path):
dic = dict()
with codecs.open(path, 'r', 'utf-8') as f:
for line in f:
s = line.split()
for i in range (0, len(s)-1):
dic[str(s[i]) + ' ' + str(s[i+1])] += 1
return dic
我得到了这个错误:
File "C:/Users/user/Anaconda3/hw2.py", line 100, in countTuples
dic[str(s[i]) + ' ' + str(s[i+1])] += 1
TypeError: list indices must be integers or slices, not str
如果我删除+=
并放置=1
一切正常,我想问题是当我试图访问一个条目来提取一个还不存在的值时?在
我能做些什么来解决这个问题?在
不需要那么难,只需使用
Counter
并使用zip
将二元组输入计数器,如:只需对代码进行最小更改的一个解决方案是使用
defaultdict
:这会产生:
^{pr2}$你的功能就是:
您可以使用^{} 使您的解决方案有效。使用
defaultdict
,可以指定键值对的值的默认类型。这允许您像+=1
那样对尚未显式创建的键进行赋值:相关问题 更多 >
编程相关推荐