While partitioning the elements in a list using GatherBy, can I correspondingly partition the elements of an unrelated list?
If we have a list like the following:
list1 = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};
And we use GatherBy
to subpartition is according to a test function
GatherBy[list1, Mod[#, 3] &]
We have as an output for this example {{1, 4, 7, 10}, {2, 5, 8, 11}, {3, 6, 9, 12}}
. See Artes' answer to my previous question: Subpartitioning elements of a list based on some h[ri] == h[rj] test
However, can we subpartition an unrelated list of the same length as list1
, some list2
with arbitrary elements, in the same manner as list1
is subpartitioned via GatherBy
?
For example, let's write some nonsense in list format:
list2 = {"It", "is", "only", "the", "morning", "the", "man", "complained", "I", "shall", "consider", "nothing"};
If we sort this list via the GatherBy
output of the first list, we would have:
list2bylist1 = {{"It", "the", "man", "shall"}, {"is", "morning", "complained", "consider"}, {"only", "the", "I", "nothing"}};
Is there a way to do this simply?
Answer
list1 = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};
list2 = {"It", "is", "only", "the", "morning", "the", "man", "complained", "I", "shall",
"consider", "nothing"};
GatherBy[Transpose[{list1, list2}], Mod[#[[1]], 3] &][[All, All, 2]]
(* {{"It", "the", "man", "shall"}, {"is", "morning", "complained", "consider"},
{"only", "the", "I", "nothing"}} *)
Comments
Post a Comment