Sort List of Rules in Numeric Order

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?

• SortBy[rulelist, Last]? – march Oct 3 '17 at 17:05
• 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. – aardvark2012 Oct 4 '17 at 10:24
• That would work. I'll try that and see. – BJParks Oct 5 '17 at 0:02

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.

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