0
$\begingroup$

I have a list with elements of the form myList = {c1 F1, c2 F2, c3 F3, ...} where c1, c2, ... are explicitly integers, and F1,F2,F3 are symbolic expressions.

How do I sort this list by the absolute values of the integers?

That is for the input {F1, 10 F2, -9 F3} the desired output is {10 F2, -9 F3, F1}

$\endgroup$
3
$\begingroup$
Clear["Global`*"]

lst = {F1, 10 F2, -9 F3, 99 F4, -23 F5};

For version 12

ReverseSortBy[lst,
 (# /. Times[n : _Integer : 1, _] :> Abs[n]) &]

(* {99 F4, -23 F5, 10 F2, -9 F3, F1} *)

For earlier versions

Reverse@SortBy[lst,
  (# /. Times[n : _Integer : 1, _] :> Abs[n]) &]

(* {99 F4, -23 F5, 10 F2, -9 F3, F1} *)

EDIT: Or slightly simpler

SortBy[lst,
 (# /. Times[n : _Integer : 1, _] :> -Abs[n]) &]

(* {99 F4, -23 F5, 10 F2, -9 F3, F1} *)
$\endgroup$
1
$\begingroup$

quick stab at it. I suspect there is better way to do this. (using Associations)

Clear["Global`*"];
lst = {F1, 10 F2, -9 F3 };
lst0 = (If[Head[#] === Symbol, {1, #}, {First[#], Rest[#]}] &) /@ lst;
lst0 = SortBy[lst0, Abs[First[#]] &, Greater];
Times @@@ lst0

Mathematica graphics

For lst = {F1, 10 F2, -9 F3 , 99 F4, -23 F5}; it gives

Mathematica graphics

This assumes in your list there are no entry with just a single number in it, each entry in the list has the form $c_i F_i$ or $F_i$, where $F_i$ is a symbol and $c_i$ is a number.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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