在mathematica中,如何返回两个列表(包括重复列表)的交集?
在mathematica中,如何找到两个列表(包括重复列表)的交集 所以,如果我有这个:在mathematica中,如何返回两个列表(包括重复列表)的交集?,math,wolfram-mathematica,Math,Wolfram Mathematica,在mathematica中,如何找到两个列表(包括重复列表)的交集 所以,如果我有这个: list1 = {1, 1, 3, 4, 5, 6, 6, 6, 7, 7, 10, 11, 11}; list2 = {1, 1, 4, 5, 5, 6, 6, 7, 7, 8, 11, 11, 13, 14}; 我想让它退回这个: IntersectionIncludingDuplicates[list1, list2] = {1, 1, 4, 5, 6, 6, 7, 7, 11, 11} 谢谢你的
list1 = {1, 1, 3, 4, 5, 6, 6, 6, 7, 7, 10, 11, 11};
list2 = {1, 1, 4, 5, 5, 6, 6, 7, 7, 8, 11, 11, 13, 14};
我想让它退回这个:
IntersectionIncludingDuplicates[list1, list2] = {1, 1, 4, 5, 6, 6, 7, 7, 11, 11}
谢谢你的帮助 编辑:已修复并已测试 您可以使用常规的
交叉点
,然后使用计数
,类似于
ConstantArray[#, Min[Count[list1, #], Count[list2, #]]] & /@
Intersection[list1, list2] // Flatten
{1,1,4,5,6,6,7,7,11,11}
以函数形式概括为任意数量的列表:
IntersectionIncludingDuplicates[lists__List] :=
ConstantArray[#,
Function[{v}, Min @@ (Count[#, v] & /@ {lists})]@#] & /@
Intersection[lists] // Flatten
IntersectionIncludingDuplicates[list1, list2]
{1,1,4,5,6,6,7,7,11,11}
这里有一个方法:
Catenate@KeyValueMap[ConstantArray]@
MapThread[Min, KeyIntersection[Counts /@ {list1, list2}]]
细分:
- 计算每个元素在每个列表中出现的次数(
)计数
- 仅保留出现在这两种情况下的元素(
)KeyCrossion
- 以较小的出现次数(
,MapThread
)复制给定元素多次(Min
)ConstantArray
- 简单易懂的代码。假设输入列表已排序
list1 = {1, 1, 3, 4, 5, 6, 6, 6, 7, 7, 10, 11, 11};
list2 = {1, 1, 4, 5, 5, 6, 6, 7, 7, 8, 11, 11, 13, 14};
IntersectionIncludingDuplicates[list1_, list2_] := Module[
{out = {}, i = j = 1},
While[i <= Length[list1] && j <= Length[list2],
If[list1[[i]] == list2[[j]],
AppendTo[out, list1[[i]]];
i++; j++,
If[list1[[i]] < list2[[j]], i++, j++]]];
out]
IntersectionIncludingDuplicates[list1, list2]
list1={1,1,3,4,5,6,6,6,7,10,11,11};
清单2={1,1,4,5,5,6,6,7,8,11,11,13,14};
IntersectionIncludingDuplicates[list1\uUx,list2\uUx]:=模块[
{out={},i=j=1},
而我