# Finding equal values in a list

Is there a way to take equal elements out of a list and their position???

An example can be

v = {13.51, 13.51, 12.36, 12.36, 12.36, 12.36, 12.85, 12.85, 12.85, 12.85}


with desired output a list like:

 {{13.51, 12.36, 12.85},{2,4,4}}


where on the left there are the elements written with the correct order and on the right how many times they repeat. The elements in the starting list are considered to be ordered. Thanks

• Does Tally[v]//Transpose not do what you want? If not, perhaps you could post the expected outcome for v and v = {1, 3, 3, 3, 4, 4, 4}? Sep 17, 2020 at 9:34

Try

v = {13.51, 13.51, 12.36, 12.36, 12.36, 12.36, 12.85, 12.85, 12.85, 12.85};
Transpose[Tally[v]]


which returns

{{13.51, 12.36, 12.85}, {2, 4, 4}}


and see if that works in every case for you. Approximate decimal numbers may sometimes cause problems when testing for equality.

Using the Query "fork-operator"

Query[All /* Transpose, {First, Length}] @ Split[v]


{{13.51, 12.36, 12.85}, {2, 4, 4}}

v = {13.51, 13.51, 12.36, 12.36, 12.36, 12.36, 12.85, 12.85, 12.85, 12.85};


Using Comap (new in 14.0)

Comap[{First, Length}] /@ Split[v]


{{13.51, 2}, {12.36, 4}, {12.85, 4}}

Transpose[%]


{{13.51, 12.36, 12.85}, {2, 4, 4}}

f = Through @* {Keys, Values} @* Counts;

f @ v

{{13.51, 12.36, 12.85}, {2, 4, 4}}


The elements in the starting list are considered to be ordered

Using Split:

Transpose[{First@#, Length@#} & /@ Split[v]]


Using SequenceReplace:

SequenceReplace[v, k : {Repeated[a_] } :> {a, Length@k}] // Transpose


Using GroupBy:

{Keys@#, Values@#} &@GroupBy[v, # &, Length]


Result:

{{13.51, 12.36, 12.85}, {2, 4, 4}}

Using SequenceCases and Repetead:

v = {13.51, 13.51, 12.36, 12.36, 12.36, 12.36, 12.85, 12.85, 12.85, 12.85};

Transpose@SequenceCases[v, s : {Repeated[x_]} :> {x, Length@s}]

(*{{13.51, 12.36, 12.85}, {2, 4, 4}}*)


Or using Count and DeleteDuplicates:

{#, Map[Count[v, #] &, #]} &@DeleteDuplicates@v

(*{{13.51, 12.36, 12.85}, {2, 4, 4}}*)

v = {13.51, 13.51, 12.36, 12.36, 12.36, 12.36, 12.85, 12.85, 12.85, 12.85};


Using PositionIndex:

Thread[List @@ # & /@ Normal@(Length /@ PositionIndex[v])]

(*{{13.51, 12.36, 12.85}, {2, 4, 4}}*)


Or equivalently:

Thread[{#1, Length@#2} & @@@ Normal[PositionIndex[v]]]

(*{{13.51, 12.36, 12.85}, {2, 4, 4}}*)


Try Union

{13.51, 13.51, 12.36, 12.36, 12.36, 12.36, 12.85, 12.85, 12.85, 12.85} // Union
(*{12.36, 12.85, 13.51}*)

{1, 3, 3, 3, 4, 4, 4} //Union
(*{1, 3, 4}*)