I have 2 lists (of lists), where most of the contained lists match. That is, the lists contained in list1 mostly match the lists contained in list2. In this simplified example each of the inner lists has 3 elements. When a sub list of list1 and a sublist of list2 have their 1st 2 values the same, I want to compare the 3rd value. I have another list, "problems", that contains the first 2 elements of each sub list that creates a problem for me. My sample code follows:
problems = {{1, 2}, {1, 3}, {2, 2}};
list1 = {{1, 2, 12}, {1, 3, 13}, {1, 2, 14}, {4, 5, 11}};
list2 = {{1, 2, 22}, {1, 3, 23}, {2, 2, 26}, {4, 5, 11}, {1, 3, 13}};
want = {{1, 2, {12, 14}, {22}}, {1, 3, {13}, {13, 23}}, {2, 2, {}, {26}}};
list1a = Flatten[(Cases[list1, {#[[1]], #[[2]], __}] & /@ problems) /. {} -> {{}}, 1]
list1b = GatherBy[list1a, If[# == {}, True, {#[[1]], #[[2]]}] &]
The list labelled "want" is what I'd like to get at the end of this. Actually, I just want to have something that will contain those 1st two elements, and then show the comparison of the 3rd elements. The GatherBy seems to be getting me closer to what I want, but I can't figure out how to correctly group it so that it looks like "want". I'm hoping that someone can suggest a better way to approach this.
Answer
Function[{x, y}, {x, y, Sequence @@ (Last /@ Cases[#, {x, y, __}] & /@ {list1, list2})}] @@@ problems
(*
{{1, 2, {12, 14}, {22}}, {1, 3, {13}, {23, 13}}, {2, 2, {}, {26}}}
*)
Comments
Post a Comment