Is there way to construct oneliner as pure function(s), so that I enter mylist
only on one place - on the end of line. And that function return the same result as last line bellow but paired with mylist
. So the result should look like this:
{{1, {8}}, {2, {2, 4, 6}}, {4, {1}}, {5, {5}}, {7, {3, 7}}}
mylist = {4, 2, 7, 2, 5, 2, 7, 1};
alldiffelem = Sort@DeleteDuplicates@mylist
(* {1, 2, 4, 5, 7} *)
(Flatten@Position[mylist, #]) & /@ alldiffelem
(* {{8}, {2, 4, 6}, {1}, {5}, {3, 7}} *)
Answer
Here is an approach using Sow
and Reap
:
Last@Reap[MapThread[Sow, {Range[Length[mylist]], mylist}], _, List]
yielding
{{4, {1}}, {2, {2, 4, 6}}, {7, {3, 7}}, {5, {5}}, {1, {8}}}
if you wish to sort:
SortBy[Last@Reap[MapThread[Sow, {Range[Length[mylist]],mylist}], _, List], First]
yielding:
{{1, {8}}, {2, {2, 4, 6}}, {4, {1}}, {5, {5}}, {7, {3, 7}}}
Comments
Post a Comment