首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >具有set的循环:键

具有set的循环:键
EN

Stack Overflow用户
提问于 2018-03-15 06:23:33
回答 1查看 48关注 0票数 0

当对一组int值执行for循环时,我会得到一个密钥错误。

以下是代码:

代码语言:javascript
复制
# 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

函数的目的有点难,但我这里的问题是:

代码语言:javascript
复制
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' 

(但有一次是“美食”,另一次是“恋童癖”,或“运动”,.

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-03-15 06:42:17

我在这些线上的两美分就是罪魁祸首。

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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49292783

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档