# How to get a description of the positions of similar elements in a list

I want to find a function F to represent the positions of identical elements in a list, which means, for example:

• F[{5,6,5,7}]={{1,3},{2},{4}}
• F[{5,6,6,5}]={{1,4},{2,3}}
• F[{5,7,5,5}]={{1,3,4},{2}}
• F[{5,6,7,8}]={{1},{2},{3},{4}}
• F[{5,5,5,5}]={{1,2,3,4}}

etc. Is there any function or implementation?

Moreover, I want to use this into an $\underbrace{n\times n\times\cdots\times n}_m$ Table t[n_,m_] (so the dimension $m$ is also an input of t), such that

• t[[i_1,...,i_m]]=Subscript[x,F[{i_1,...,i_m}]]

where $1\le i_1,\cdots,i_m\le n$. How can I implement it?

Thanks :)

• What is a "partition situation of a list"? Your example is unclear. Give an explanation as well as examples. – David G. Stork Jun 22 '17 at 0:12
• Ohhh.... position situation (not partition situation)! Got it! – David G. Stork Jun 22 '17 at 0:32
• Thanks for your edit! Indeed I don't know how to describe it accurately. – Zigzag1263 Jun 22 '17 at 19:58
• The first part of this question is a duplicate of How to efficiently find positions of duplicates? – kglr Jul 23 '17 at 14:28

To get the positions of the same elements in a list you can use PositionIndex

f[x_] := Values@PositionIndex[x]


Test:

f[{5,6,5,7}]
f[{5,6,6,5}]


{{1,3},{2},{4}}

{{1,4},{2,3}}

• To make it more simple, try f=Values@*PositionIndex – Wjx Jun 22 '17 at 0:29
• @Wjx Thanks for the suggestion. – Anjan Kumar Jun 22 '17 at 0:44

One possibility:

F[list_]:=Values @ GroupBy[
Identity,
Keys
]


F[{5,6,5,7}]
F[{5,6,6,5}]
F[{5,7,5,5}]
F[{5,6,7,8}]
F[{5,5,5,5}]


{{1, 3}, {2}, {4}}

{{1, 4}, {2, 3}}

{{1, 3, 4}, {2}}

{{1}, {2}, {3}, {4}}

{{1, 2, 3, 4}}

ClearAll[f]
f[lst_] := GatherBy[Range @ Length @ lst, lst[[#]]&]
(* or  f[lst_] := Values @ GroupBy[Range @ Length @ lst, lst[[#]]&] *)

mat = {{5, 6, 5, 7}, {5, 6, 6, 5}, {5, 7, 5, 5}, {5, 6, 7, 8}, {5, 5, 5, 5}};
Grid[Prepend[{#, f@#} & /@ mat, {"list", "f[list]"}], Dividers -> All] Subscript[x, f@#] & /@ mat 