3

I would like to make a function that takes in a list of integers and returns a partition of the indices of the list, based on the elements of the list.

For instance:

{1,3,3,7} --> { {1}, {2,3}, {4}}
{3,1,3} --> {{1,3}, {2}}

I can think of messy ways to do this, but is there a natural way to do this in Mathematica?

4

3 回答 3

2

I would use:

indicies[x_] := Reap[MapIndexed[Sow[#2, #] &, x]][[2, All, All, 1]]

This will be much faster than repeatedly using Position, on a long lists with many unique elements. Example:

list = RandomInteger[9999, 10000];

Timing[
  result1 =
    Function[x, (Flatten@Position[x, #] &) /@ DeleteDuplicates[x]]@list;
]
{3.463, Null}
Timing[
  result2 = indicies @ list;
]
{0.031, Null}
result1 === result2
True

TomD suggested using the newer GatherBy in place of Sow and Reap. This is even faster on long lists with little repetition.

indicies2[x_] := GatherBy[List ~MapIndexed~ x, First][[All, All, 2, 1]]

list2 = RandomInteger[99999, 100000];

Do[indicies @ list2, {10}] // Timing
Do[indicies2 @ list2, {10}] // Timing
{5.523, Null}

{2.823, Null}

Speed is more similar on lists with greater repetition:

list3 = RandomInteger[99, 100000];

Do[indicies @ list3, {10}] // Timing
Do[indicies2 @ list3, {10}] // Timing
{1.716, Null}

{1.607, Null}

If going for pure speed one must recognize that MapIndexed is not optimized for packed arrays, therefore Range and Transpose will be considerably faster in that case:

indicies3[x_] := GatherBy[{x, Range@Length@x}\[Transpose], First][[All, All, 2]]

Do[indicies3 @ list2, {10}] // Timing
{1.981, Null}
Do[indicies3@list3, {10}] // Timing  (* big difference here *)
{0.125, Null}
于 2012-06-17T02:23:53.133 回答
1

One possibility:

Function[x, (Flatten@Position[x, #] &) /@ DeleteDuplicates[x]]@{1, 3, 
  3, 7}

giving

(*  {{1}, {2, 3}, {4}  *)

Another example:

lst = {1, 3, 3, 3, 7, 4, 3};
Function[x, (Flatten@Position[x, #] &) /@ DeleteDuplicates[x]]@lst

giving:

(*{{1}, {2, 3, 4, 7}, {5}, {6}}*)
于 2012-06-16T23:14:28.720 回答
0

Yet another approach:

f[x_] := Flatten[x~Position~First@#] & /@ Gather@x
于 2012-06-22T09:22:51.243 回答