【发布时间】:2021-01-06 23:19:13
【问题描述】:
我有这个问题:
我有这段代码试图计算文本文件中的二元组。 if 语句检查元组是否在字典中。如果是,则值(计数器)加一。如果不存在,代码应该创建一个键值对,元组为键,值为 1。
for i in range(len(temp_list)-1):
temp_tuple=(temp_list[i], temp_list[i+1])
if bigramdict[temp_tuple] in bigramdict:
bigramdict[temp_tuple] = bigramdict[temp_tuple]+1
else:
bigramdict[temp_tuple] = 1
但是,每当我运行代码时,它都会在第一个元组上引发 KeyError。 据我了解,当 dict 中的键不存在时会抛出 KeyError ,这里就是这种情况。这就是为什么我有 if 语句来查看是否有密钥。正常情况下,程序应该看到没有key,然后去else创建一个。
但是,它卡在 if 上并抱怨缺少键。
为什么它不识别这是一个条件语句?
请帮忙。
【问题讨论】:
-
这能回答你的问题吗? I'm getting Key error in python
-
bigramdict = Counter(zip(temp_list, temp_list[1:]))。 (这不是最有效的方法,而是最短且最容易理解的方法。)
标签: python python-3.x dictionary if-statement tuples