Aligning two lists
If the lists are long (several hundred or more), Alternatives
will get to be slow. Here's another way that will be faster on longer lists:
align[list1_, list2_] := Module[{base, replace1, replace2},
base = Union[First /@ list1, First /@ list2];
With[{arg = First[#]}, replace1[arg] = #] & /@ list1;
replace1[_] = {0, {}};
With[{arg = First[#]}, replace2[arg] = #] & /@ list2;
replace2[_] = {0, {}};
{replace1 /@ base, replace2 /@ base}
Example:
data = {"that", "natural", "cowards", "delay", "country", "himself",
"my", "will", "cast", "office", "native", "is", "awry", "s", "ay"};
l1 = {#, ToCharacterCode[#]} & /@ Sort@RandomSample[data, 10]
l2 = {#, {StringLength[#]}} & /@ Sort@RandomSample[data, 10]
(*
{{"ay", {97, 121}}, {"cast", {99, 97, 115, 116}},
{"cowards", {99, 111, 119, 97, 114, 100, 115}}, {"delay", {100, 101, 108, 97, 121}},
{"himself", {104, 105, 109, 115, 101, 108, 102}}, {"is", {105, 115}},
{"my", {109, 121}}, {"native", {110, 97, 116, 105, 118, 101}},
{"that", {116, 104, 97, 116}}, {"will", {119, 105, 108, 108}}}
{{"cast", {4}}, {"cowards", {7}}, {"delay", {5}}, {"is", {2}}, {"my", {2}},
{"native", {6}},{"natural", {7}}, {"s", {1}}, {"that", {4}}, {"will", {4}}}
*)
align[l1, l2];
Grid[Transpose@{newl1, newl2}]
I'm late to the party but I like this kind of problem so I'm going to answer anyway.
I propose this:
f1[a_List, b_List, fill_: {0, {}}] :=
With[{all = a ⋃ b},
Replace[
Join[all, #] ~GatherBy~ First,
{{_} -> fill, {__, x_} :> x},
1
] & /@ {a, b}
]
Test:
a = {{1, 7}, {3, 7}, {5, 2}, {8, 7}};
b = {{3, 1}, {6, 6}, {8, 7}, {9, 3}};
f1[a, b] // Grid
$ \begin{array}{cccccc} \{1,7\} & \{3,7\} & \{5,2\} & \{0,\{\}\} & \{8,7\} & \{0,\{\}\} \\ \{0,\{\}\} & \{3,1\} & \{0,\{\}\} & \{6,6\} & \{8,7\} & \{9,3\} \end{array} $
Note that this sample includes keys with both identical ({8, 7}
) and divergent ({3, 7}
, {3, 1}
) data.
TemporalData + ResamplingMethod
ClearAll[timeAlign]
timeAlign = Module[{td = TemporalData[{##}, ResamplingMethod -> {"Constant", {}}], times},
times = Union @@ td["TimeList"];
Thread[{times, #}] & /@ Through @ td["PathFunctions"] @ times]&;
Example: using Mr.Wizard's example lists
a = {{1, 7}, {3, 7}, {5, 2}, {8, 7}};
b = {{3, 1}, {6, 6}, {8, 7}, {9, 3}};
timeAlign[a, b]
{{{1, 7}, {3, 7}, {5, 2}, {6, {}}, {8, 7}, {9, {}}},
{{1, {}}, {3, 1}, {5, {}}, {6, 6}, {8, 7}, {9, 3}}}
Association + KeyUnion
KeyValueMap[List]/@KeyUnion[Association/@(Rule @@@ # & /@ {a, b})]/. _Missing -> {}
{{{1, 7}, {3, 7}, {5, 2}, {8, 7}, {6, {}}, {9, {}}},
{{1, {}}, {3, 1}, {5, {}}, {8,7}, {6, 6}, {9, 3}}}