Python 字典中数组的交集

2024-03-27

我有数组字典,如下所示:

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。 作为第一步,我从空数组中清除了字典,就像

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

So, 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])}

为了找到拦截,我尝试使用元组方法,如下所示:

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

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

预期结果应该是:[5, 111]

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


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

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

or with map并且没有for loop:

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

result

[5, 111]
  • 迭代值(忽略键)
  • 将每个 numpy 数组转换为set(转换为tuple也有效,但是intersection无论如何都会将它们转换为集合)
  • 将批次传递给intersection带参数解包

我们甚至可以通过在每个数组上创建集合并使用以下方法过滤掉空集合来摆脱步骤 1filter:

result_dic = list(set.intersection(*(filter(None,map(set,y_dict.values())))))

这是为了一句台词,但在现实生活中,表达式可能会被分解,以便它们更具可读性和可评论性​​。这种分解还可以帮助我们避免在不传递任何参数时发生的崩溃(因为没有非空集),这会破坏相交集的智能方法(首先在找到多个集合的交集的最佳方法? https://stackoverflow.com/questions/2541752/best-way-to-find-the-intersection-of-multiple-sets).

只需预先创建列表,仅当列表不为空时才调用交集。如果为空,则只需创建一个空集:

non_empty_sets = [set(x) for x in y_dict.values() if x.size]
result_dic = list(set.intersection(*non_empty_sets)) if non_empty_sets else set()
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Python 字典中数组的交集 的相关文章

随机推荐