# Arrange an expression based on variables' names

I have a problem of arranging an expression as shown in the following picture. The first expression exp is derived from other functions and equations. I want to get the result like (2) expArranged, which is formed from the constant, the functions of x1 and the functions of x2 in every terms of exp.

Can you give the approach to obtain the result? Thank you.

Note:

The name expArranged in expression (2) is only for the convenience to express my problem, not variable symbol.

The codes have been presented in the end of the post.

Picture

Codes and the method converting it to standard form

exp = a Subscript[Q, i][x1] Subscript[Q, j][x2] Subscript[Q, m][x1] Subscript[Q, n][x2] + b DiracDelta[x1] Subscript[Q, i][x1] Subscript[Q, j][x2] Subscript[Q, n][x2] Derivative[1][Subscript[Q, m]][x1] + c DiracDelta[x2] Subscript[Q, i][x1] Subscript[Q, j][x2] Subscript[Q, m][x1] Derivative[1][Subscript[Q, n]][x2] + d Subscript[Q, i][x1] Subscript[Q, j][x2] Subscript[Q, n][x2] (Subscript[Q, m]^\[Prime]\[Prime])[x1];(*1*)
expArranged = {{a, Subscript[Q, i][x1] Subscript[Q, m][x1], Subscript[Q, j][x2] Subscript[Q, n][x2]}, {b, DiracDelta[x1] Subscript[Q, i][x1] Derivative[1][Subscript[Q, m]][ x1], Subscript[Q, j][x2] Subscript[Q, n][x2]}, {c, Subscript[Q, i][x1] Subscript[Q, m][x1], DiracDelta[x2] Subscript[Q, j][x2] Derivative[1][Subscript[Q, n]][ x2]}, {d, Subscript[Q, i][x1] (Subscript[Q, m]^\[Prime]\[Prime])[x1], Subscript[Q, j][x2] Subscript[Q, n][x2]}};(*2*)
(*end here*)

• Times @@@ {Cases[#, Except[_[x1] | _[x2]]], Cases[#, _[x1]], Cases[#, _[x2]]} & /@ List @@ exp Commented Jan 14, 2022 at 13:46
• @Hausdorff, Thanks for your concise and excellent solution. Commented Jan 14, 2022 at 14:27

eArranged = Values @
GroupBy[SortBy[First[#, #] &] @ Apply[List] @ #, First[#, #] &, Times @@ # &] & /@
MonomialList[exp];


\$p = Cases[x1 | x2];
eArranged2 = Times @@@ GatherBy[SortBy[List @@ ##, $$p],$$p] & /@ MonomialList[exp];