在对一组int值执行for循环时,我得到了一个Keyerror。
以下是代码:
# groupes : dict[str:set[int]]
groupes = {'cinephiles':{802,125,147,153}, \
'travaux manuels':{125,802,153}, \
'cuisine':{153,147,802}, \
'sport':{153,538,802}}
# This first function helps me for the second one
def proximite_groupes(group, hobby_1, hobby_2):
"""
dict[str:set[int]] * str * str -> float
"""
# intersection_set : set[int]
intersection_set = set()
# union_set : set[int]
union_set = set()
# cle : int
for cle in group[hobby_1]:
if cle in group[hobby_2]:
intersection_set.add(cle)
for cle in group[hobby_1]:
if cle not in union_set:
union_set.add(cle)
for cle in group[hobby_2]:
if cle not in union_set:
union_set.add(cle)
return len(intersection_set) / len(union_set)
def fusion_groupes(group):
"""
dict[str:set[int]] -> dict[str:set[int]]
"""
# similarite_max : int
similarite_max = 0.0
# str_1 : str
# str_2 : str
# str_1_final : str
str_1_final = ''
str_2_final = ''
# str_1_final : str
# str_final : str
str_final = ' '
# final_dict : dict[str:set[int]]
final_dict = group
# intersection_set : set[int]
intersection_set = set()
for str_1 in group:
for str_2 in group:
if str_1 != str_2:
if proximite_groupes(group, str_1, str_2) > similarite_max:
similarite_max = proximite_groupes(group, str_1, str_2)
str_final = str_1 + '_' + str_2
str_1_final = str_1
str_2_final = str_2
del final_dict[str_1_final]
del final_dict[str_2_final]
# Creation ensemble union
for cle in group[str_1_final]:
if cle in group[str_2_final]:
intersection_set.add(cle)
final_dict[str_final] = intersection_set
return final_dict
这个功能的目的有点困难,但我的问题是:
File "<input>", line 1, in <module>
File "<input>", line 261, in fusion_groupes (note that the line would not be the same for you because my program has more lines)
KeyError: 'cuisine'
(但有一次它的烹饪&#39;,另一次是它的电影&#39;或者&#39;运动&#39;,......
答案 0 :(得分:1)
我在这些方面的两分钱是罪魁祸首
final_dict = group
del final_dict[str_1_final]
del final_dict[str_2_final]
。
这与python不会将名为group的字典深度复制到final_dict这一事实有关。相反,final_dict只是引用组。因此,当您从final_dict中删除密钥时,它也会从组中删除。它下面的代码:
for cle in group[str_1_final]:
。
失败。
以下是发生的事件的样本:https://trinket.io/python/64f20460d9