4
$\begingroup$

I have a list of rules,

rulelist ={$x1 -> 1, $x10 -> 15, $x11 -> 1, $x2 -> 6, $x3 -> 15, $x4 -> 15, $x5 -> 10, $x6 -> 60, $x7 -> 20, $x8 -> 15, $x9 -> 45}

Trying SortBy[rulelist, Greater] keeps the rulelist the way it is, and trying SortBy[rulelist, Last] gives

{$x1 -> 1, $x11 -> 1, $x2 -> 6, $x5 -> 10, $x10 -> 15, $x3 -> 15, $x4 -> 15, $x8 -> 15, $x7 -> 20, $x9 -> 45, $x6 -> 60}

How can I order these rules in numerical instead of canonical order?

$\endgroup$
3
  • $\begingroup$ SortBy[rulelist, Last]? $\endgroup$
    – march
    Commented Oct 3, 2017 at 17:05
  • $\begingroup$ Would an answer that let you replace, say, $x1 with $x01 work for you? By renaming the variables in that way, a standard Sort would do the job. $\endgroup$ Commented Oct 4, 2017 at 10:24
  • $\begingroup$ That would work. I'll try that and see. $\endgroup$
    – BJParks
    Commented Oct 5, 2017 at 0:02

1 Answer 1

2
$\begingroup$

You can define a better ordering function in your SortBy. Assuming that all your rules look like $xnnnn where n is a digit, the ToExpression@StringTake[ToString[#[[1]]], {3, -1}] & would work.

SortBy[rulelist, ToExpression@StringTake[ToString[#[[1]]], {3, -1}] &]
(* {$x1 -> 1, $x2 -> 6, $x3 -> 15, $x4 -> 15, $x5 -> 10, $x6 -> 
  60, $x7 -> 20, $x8 -> 15, $x9 -> 45, $x10 -> 15, $x11 -> 1} *)

That's very straightforward way, a more elegant way probably exists.

Brief explanation:

#[[1]] takes left side of your rule (you can replace it with First[#])

ToString makes a string from the expression

StringTake[ ,{3,-1}] takes all characters except first two (removes "$x")

ToExpression makes a number out of string, this number is used to order by.

$\endgroup$
3
  • $\begingroup$ That's perfect! I'll definitely look at the documentation and see why this works too. Thank you! $\endgroup$
    – BJParks
    Commented Oct 3, 2017 at 17:11
  • $\begingroup$ @BJParks I added some explanation. Consider upvoting/accepting the answer if you find it useful. $\endgroup$
    – BlacKow
    Commented Oct 3, 2017 at 17:18
  • $\begingroup$ Thanks again for your help; the explanation is greatly appreciated! $\endgroup$
    – BJParks
    Commented Oct 5, 2017 at 0:03

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.