6
$\begingroup$

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

$\endgroup$
1
  • 1
    $\begingroup$ 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}? $\endgroup$
    – user1066
    Sep 17, 2020 at 9:34

8 Answers 8

7
$\begingroup$

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.

$\endgroup$
3
$\begingroup$

Using the Query "fork-operator"

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

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

$\endgroup$
3
$\begingroup$
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}}

$\endgroup$
2
$\begingroup$
f = Through @* {Keys, Values} @* Counts;

f @ v
{{13.51, 12.36, 12.85}, {2, 4, 4}}
$\endgroup$
1
$\begingroup$

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}}

$\endgroup$
1
$\begingroup$

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}}*)
$\endgroup$
1
$\begingroup$
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}}*)
$\endgroup$
0
$\begingroup$

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}*) 
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.