[英]Python intersection of arrays in dictionary
我有像这样的数组字典:
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}
所以, 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())))
或者使用map
而没有for
循环:
result_dic = list(set.intersection(*(map(set,dic.values()))))
结果
[5, 111]
set
(转换为tuple
也有效,但intersection
无论如何都会将它们转换为集合)intersection
参数解包的intersection
我们甚至可以通过在每个数组上创建集合并使用filter
过滤掉空的集合来摆脱第 1 步:
result_dic = list(set.intersection(*(filter(None,map(set,y_dict.values())))))
这是为了单行,但在现实生活中,表达式可能会被分解,因此它们更具可读性和可评论性。 这种分解也可以帮助我们避免在不传递参数时发生的崩溃(因为没有非空集),这会破坏相交集的智能方式(首先在寻找多个集的交集的最佳方法中描述? )。
只需事先创建列表,只有当列表不为空时才调用交集。 如果为空,只需创建一个空集:
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()
您应该在这里使用 numpy 的交集,而不是直接在 Python 中使用。 并且您需要为空交叉点添加特殊处理。
>>> intersection = None
>>> for a in y_dict.values():
... if a.size:
... if intersection is None:
... intersection = a
... continue
... intersection = np.intersect1d(intersection, a)
...
>>> if intersection is not None:
... print(intersection)
...
[ 5 111]
对于intersection is None
的情况,这意味着y_dict
中的所有数组的大小都为零(没有元素)。 在这种情况下,交集没有明确定义,您必须自己决定代码在这里应该做什么 - 可能会引发异常,但这取决于用例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.