8
$\begingroup$

A quick question on list ordering, how can I easily get the ordering of the list, so that, for

{0, Sqrt[3], 2 Sqrt[3], Sqrt[3], 3, 2 Sqrt[3]}

I get

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

Ordering does not seem to work.

Edit: Thank you for all the wonderful answers. What might be the best way to test which one is the fastest, maybe RepeatedTiming?

$\endgroup$
0

5 Answers 5

6
$\begingroup$
list = {0, Sqrt[3], 2 Sqrt[3], Sqrt[3], 3, 2 Sqrt[3]}

list /. Union @ Flatten @
   MapIndexed[
    #1 -> #2[[1]] &,
    Split @ SortBy[N] @ list,
    {2}]

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

Also

With[{x = N @ list},
 Flatten @ Replace[x, MapIndexed[Rule] @ Union[x], {1}]]

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

$\endgroup$
2
  • $\begingroup$ Thanks. Can you compare it with my answer? Is this faster? $\endgroup$
    – sam wolfe
    Feb 17 at 0:30
  • $\begingroup$ With list = Flatten@Table[list, {100000}] my answer is almost twice as fast $\endgroup$
    – eldo
    Feb 17 at 0:39
6
$\begingroup$

Using Lookup:

list = {0, Sqrt[3], 2 Sqrt[3], Sqrt[3], 3, 2 Sqrt[3]}

a1 = DeleteDuplicates@SortBy[list, N]
rules = Thread[a1 -> Range@Length@a1]
Lookup[rules, list]

Result:

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

$\endgroup$
6
$\begingroup$

Just an alternative, combining OrderingBy with DeleteDuplicates

list = {0, Sqrt[3], 2 Sqrt[3], Sqrt[3], 3, 2 Sqrt[3]};

list /. Thread[# -> OrderingBy[#, N]]&@DeleteDuplicates@list

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

$\endgroup$
5
$\begingroup$
l = {0, Sqrt[3], 2  Sqrt[3], Sqrt[3], 3, 2  Sqrt[3]};

Using Split, SortBy and Thread:

l /.Rule @@@ Splice@*Thread /@ Thread[{#, Range@Length@#}] &@Split@SortBy[N]@l

(*{1, 2, 4, 2, 3, 4}*)
$\endgroup$
2
  • $\begingroup$ But I want the same numbers to correspond to the same ranks. Perhaps ordering is not the word? So 0->1, Sqrt[3]->2, 3->3 and 2 Sqrt[3]-> 4 $\endgroup$
    – sam wolfe
    Feb 17 at 0:00
  • $\begingroup$ @samwolfe Your solution is still faster. $\endgroup$ Feb 17 at 2:02
4
$\begingroup$
rankList[list_] := 
 Replace[#, PositionIndex[Sort@DeleteDuplicates@#][[All, 1]], 1] &@
  N[list]

seems to do the trick, though I need to use N.

$\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.