字典中的Python数组交集 [英] Python intersection of arrays in dictionary

查看:111
本文介绍了字典中的Python数组交集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有数组字典,例如:

y_dict= {1: np.array([5, 124, 169, 111, 122, 184]),
         2: np.array([1, 2, 3, 4, 5, 6, 111, 184]), 
         3: np.array([169, 5, 111, 152]), 
         4: np.array([0, 567, 5, 78, 90, 111]),
         5: np.array([]),
         6: np.array([])}

我需要在我的字典中找到数组的拦截:y_dict. 第一步,我从空数组中清除了字典,就像

I need to find interception of arrays in my dictionary: y_dict. As a first step I cleared dictionary from empty arrays, as like

dic = {i:j for i,j in y_dict.items() if np.array(j).size != 0}

因此,dic具有以下视图:

dic = { 1: np.array([5, 124, 169, 111, 122, 184]),
        2: np.array([1, 2, 3, 4, 5, 6, 111, 184]), 
        3: np.array([169, 5, 111, 152]), 
        4: np.array([0, 567, 5, 78, 90, 111])}

要找到拦截,我尝试使用元组方法,例如:

To find interception I tried to use tuple approach as like:

result_dic = list(set.intersection(*({tuple(p) for p in v} for v in dic.values())))

实际结果为空列表:[];

Actual result is empty list: [];

预期结果应为:[5, 111]

您能帮我在字典中找到数组的交集吗?谢谢

Could you please help me to find intersection of arrays in dictionary? Thanks

推荐答案

您发布的代码过于复杂且错误,因为还需要进行一次额外的内部迭代.您想这样做:

The code you posted is overcomplex and wrong because there's one extra inner iteration that needs to go. You want to do:

result_dic = list(set.intersection(*(set(v) for v in dic.values())))

或带有map且没有for循环:

result_dic = list(set.intersection(*(map(set,dic.values()))))

结果

[5, 111]

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆