当我们需要了解两个或多个数据集的共同值、互斥值或唯一值时,就需要创建交集、差异和并集。对于本月,创建三个函数:
- 交集( aList , bList ) – 返回aList和bList中包含的值列表。
- Difference ( aList , bList ) – 返回两个列表。第一个包含aList中但不在bList中的值,第二个包含bList中不在aList中的值。
- union ( aList , bList ) – 返回aList和bList中所有值的列表,删除所有重复项。
例如,如果:
aList = {“a”,“b”,“c”,“d”,“e”,“e”}
bList = {“a”,“a”,“c”,“f”,“g”}
然后,
交集(aList,bList)=> {“a”,“c”}
差异(aList,bList)=> {{“b”,“d”,“e”},{“f”,“g”}}
union(aList,bList) => {“a”,“b”,“c”,“d”,“e”,“f”,“g”}
为了获得额外的学分,请扩展交集和并集以获取三个或更多列表的列表。
使用关联数组和递归。该代码可能不是最容易理解的,因为我不是:使用明确命名的支持变量,使用递归和关联数组,还缺少所有注释。
Names Default To Here(1);
intersection = function({temp_list}, {Default Local},
Try(
tempAa = Associative Array(temp_list[1]);
tempAa << Intersect(AssociativeArray(temp_list[2])),
return("not enough lists provided");
);
If(N Items(temp_list) == 2,
return(tempAa << get keys);
);
If(N Items(temp_list) > 2,
recurse(Insert(EvalList({tempAa << get keys}), Remove(temp_list, 1,2)))
);
);
difference = function({firstList, secondList}, {Default Local},
tempAaFirst = Associative Array(firstList);
tempAaSecond = Associative Array(secondList);
tempAaFirst << Remove(Associative Array(secondList));
tempAaSecond << Remove(Associative Array(firstList));
return(Eval List({tempAaFirst << get keys, tempAaSecond << get keys}));
);
union = function({temp_list}, {Default Local},
Try(
Insert Into(temp_list[1], temp_list[2]),
return("not enough lists provided");
);
If(N Items(temp_list) == 2,
return(Associative Array(temp_list[1]) << get keys);
);
If(N Items(temp_list) > 2,
recurse(Insert(EvalList({Associative Array(temp_list[1]) << get keys}), Remove(temp_list, 1,2)))
);
);
//test cases
Clear log();
aList = {"a","b","c","d","e","e"};
bList = {"a","a","c","f","g"};
cList = {"a", "b", "c", "h"};
dList = {"i", "j", "k"};
Print("intersection()");
Show(intersection(Eval List({aList})));
Show(intersection(Eval List({aList, bList})));
Show(intersection(Eval List({aList, bList, cList})));
Show(intersection(Eval List({aList, bList, cList, dList})));
Print("\!Ndifference()");
Show(difference(aList, bList));
Print("\!Nunion()");
Show(union(Eval List({aList})));
Show(union(Eval List({aList, bList})));
Show(union(Eval List({aList, bList, cList})));
Show(union(Eval List({aList, bList, cList, dList})));至少在使用关联数组时删除重复值时可能会有点慢,至少在使用 Summarize 从数据表获取唯一值时会变得更快。