在对一组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'
(但一次是“美食”,另一次是“电影爱好者”,或“运动”。。。你知道吗
我的两分钱是罪魁祸首。
final_dict = group del final_dict[str_1_final] del final_dict[str_2_final]
.这与python没有将名为group的字典深度复制到final目录有关,final目录只是引用group。因此,当您从最终目录中删除密钥时,它也会从组中删除。下面的代码:
for cle in group[str_1_final]:
.失败。
下面是所发生事情的示例:https://trinket.io/python/64f20460d9
相关问题 更多 >
编程相关推荐