TransWikia.com

Stop Canonical Ordering of Output List

Mathematica Asked by PRG on April 4, 2021

I’m working with the code below, which works well for my purposes; however, instead of the canonical ordering seen in the output, I want the output produced in the order I give in the Cases line of code. Any help is most appreciated.

ClearAll;
m = {{N11, "x"}, {N12, "y"}, {N19, "z"}, {N20, "w"}, {N41, 
    "exz"}, {N42, "jy"}, {N49, "br"}, {N50, "mew"}, {N61, "qr"}, {N62,
     "xqe"}, {N539, "ycf"}, {N551, "pyu"}, {N559, "wq"}, {N560, 
    "hra"}};
Cases[m, {N19 | N560 | N41 | N61 | N551 | N20 | N539, __}];
TableForm[%]

Output from the above code

N19 z
N20 w
N41 exz
N61 qr
N539 ycf
N551 pyu
N560 hra

2 Answers

alternatives = N19 | N560 | N41 | N61 | N551 | N20 | N539;

You can map Cases over the list of alternatives:

Join @@ Cases[{#, __}][m] & /@ (List @@ alternatives);

TableForm @ %

enter image description here

Alternatively, sort the output of Cases by the position in alternatives of the first column elements:

SortBy[PositionIndex[List @@ alternatives]@*First][Cases[m, {alternatives, __}]];

% // TableForm

enter image description here

Correct answer by kglr on April 4, 2021

The cases will be found in the order they occur in m. If each case is unique, as in the example, the following can be used:

Sort[
 Cases[m, {N19 | N560 | N41 | N61 | N551 | N20 | N539, __}]
 ][[Ordering[N19 | N560 | N41 | N61 | N551 | N20 | N539]]]

Answered by Michael E2 on April 4, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP