Selecting elements from a list where the order is set by another listHow to order a list to match the order of another list?How to sum elements of a list of lists?Creating sums of elements from a listDeleting one of each chosen elements in a list containing duplicatesGrouping the first two elements in a list of ordered triplesHow to pair-up nearest elements from different listsMatching the order of a master list of lists from a random list of listsFinding the most common n-tuples of a list of lists where order does not matterDelete elements of a list that appear in another listRemoving zeros from a list of equationsSelecting elements satisfying a conditionSelecting from a matrix according to elements of a column — efficiency and speed?

Who commanded or executed this action in Game of Thrones S8E5?

How to make a not so good looking person more appealing?

Why were the bells ignored in S8E5?

Slice a list based on an index and items behind it in python

How does Ctrl+c and Ctrl+v work?

Is random forest for regression a 'true' regression?

Formal Definition of Dot Product

Could there be something like aerobatic smoke trails in the vacuum of space?

Why did the UK remove the 'European Union' from its passport?

How to describe a building set which is like LEGO without using the "LEGO" word?

Does addError() work outside of triggers?

What do you call the hair or body hair you trim off your body?

To whom did Varys write those letters in Game of Thrones S8E5?

With today's technology, could iron be smelted at La Rinconada?

c++ conditional uni-directional iterator

Why are goodwill impairments on the statement of cash-flows of GE?

Which creature is depicted in this Xanathar's Guide illustration of a war mage?

Why doesn't Iron Man's action affect this person in Endgame?

Will consteval functions allow template parameters dependent on function arguments?

What is Feeblemind's effect on Ability Score Improvements?

Single word that parallels "Recent" when discussing the near future

I recently started my machine learning PhD and I have absolutely no idea what I'm doing

Wireless headphones interfere with Wi-Fi signal on laptop

Do people who work at research institutes consider themselves "academics"?



Selecting elements from a list where the order is set by another list


How to order a list to match the order of another list?How to sum elements of a list of lists?Creating sums of elements from a listDeleting one of each chosen elements in a list containing duplicatesGrouping the first two elements in a list of ordered triplesHow to pair-up nearest elements from different listsMatching the order of a master list of lists from a random list of listsFinding the most common n-tuples of a list of lists where order does not matterDelete elements of a list that appear in another listRemoving zeros from a list of equationsSelecting elements satisfying a conditionSelecting from a matrix according to elements of a column — efficiency and speed?













11












$begingroup$


I have two lists, list A and list B. All of the elements of A are members of B. The order of B is fixed but the order of A is random. I need to arrange the elements in A as given in B.



Example let A



A=5,2,8


and B is



B=9,2,6,8,5,1


I need to reorder A to be:



A=2,8,5


I'm looking for a clever one-liner. This is similar to How to order a list to match the order of another list? but there the two lists have the same length. I tried some variations on adding some padding.



From the clever solutions below I have settled on using:



OrderLike[A_List,B_List]:=Cases[Alternatives @@ A]@B;


Which has been shown to be the fasted and most poetic.
(However, Its poeticness is a subjective matter unlike its speed.)










share|improve this question











$endgroup$
















    11












    $begingroup$


    I have two lists, list A and list B. All of the elements of A are members of B. The order of B is fixed but the order of A is random. I need to arrange the elements in A as given in B.



    Example let A



    A=5,2,8


    and B is



    B=9,2,6,8,5,1


    I need to reorder A to be:



    A=2,8,5


    I'm looking for a clever one-liner. This is similar to How to order a list to match the order of another list? but there the two lists have the same length. I tried some variations on adding some padding.



    From the clever solutions below I have settled on using:



    OrderLike[A_List,B_List]:=Cases[Alternatives @@ A]@B;


    Which has been shown to be the fasted and most poetic.
    (However, Its poeticness is a subjective matter unlike its speed.)










    share|improve this question











    $endgroup$














      11












      11








      11


      2



      $begingroup$


      I have two lists, list A and list B. All of the elements of A are members of B. The order of B is fixed but the order of A is random. I need to arrange the elements in A as given in B.



      Example let A



      A=5,2,8


      and B is



      B=9,2,6,8,5,1


      I need to reorder A to be:



      A=2,8,5


      I'm looking for a clever one-liner. This is similar to How to order a list to match the order of another list? but there the two lists have the same length. I tried some variations on adding some padding.



      From the clever solutions below I have settled on using:



      OrderLike[A_List,B_List]:=Cases[Alternatives @@ A]@B;


      Which has been shown to be the fasted and most poetic.
      (However, Its poeticness is a subjective matter unlike its speed.)










      share|improve this question











      $endgroup$




      I have two lists, list A and list B. All of the elements of A are members of B. The order of B is fixed but the order of A is random. I need to arrange the elements in A as given in B.



      Example let A



      A=5,2,8


      and B is



      B=9,2,6,8,5,1


      I need to reorder A to be:



      A=2,8,5


      I'm looking for a clever one-liner. This is similar to How to order a list to match the order of another list? but there the two lists have the same length. I tried some variations on adding some padding.



      From the clever solutions below I have settled on using:



      OrderLike[A_List,B_List]:=Cases[Alternatives @@ A]@B;


      Which has been shown to be the fasted and most poetic.
      (However, Its poeticness is a subjective matter unlike its speed.)







      list-manipulation core-language






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited May 4 at 19:15







      c186282

















      asked May 4 at 1:49









      c186282c186282

      868613




      868613




















          2 Answers
          2






          active

          oldest

          votes


















          13












          $begingroup$

          SortBy[Position[B, #]&]@A



          2, 8, 5




          and



          SortBy[PositionIndex @ B] @ A (* thanks: WReach *)



          2, 8, 5




          Also,



          Cases[Alternatives @@ A] @ B
          Select[MatchQ[Alternatives @@ A]] @ B
          DeleteCases[Except[Alternatives @@ A]] @ B


          Update: Some timing comparisons:



          f1[a_, b_] := SortBy[FirstPosition[b, #] &]@a;
          f2[a_, b_] := SortBy[Position[b, #] &]@a;
          f3[a_, b_] := SortBy[PositionIndex @ b]@a;
          f4[a_, b_] := Cases[Alternatives @@ a] @ b;
          f5[a_, b_] := Select[MatchQ[Alternatives @@ a]] @ b;
          f6[a_, b_] := DeleteCases[Except[Alternatives @@ a]] @b;
          funcs = "f1", "f2", "f3", "f4", "f5", "f6";

          SeedRandom[1]
          nb = 10000;
          na = 5;
          b = RandomSample[Range[10^6], nb];
          a = RandomSample[b, na];
          t1 = First@RepeatedTiming[r1 = f1[a, b];];
          t2 = First@RepeatedTiming[r2 = f2[a, b];];
          t3 = First@RepeatedTiming[r3 = f3[a, b];];
          t4 = First@RepeatedTiming[r4 = f4[a, b];];
          t5 = First@RepeatedTiming[r5 = f5[a, b];];
          t6 = First@RepeatedTiming[r6 = f6[a, b];];
          r1 == r2 == r3 == r4 == r5 == r6



          True




          timings = t1, t2, t3, t4, t5, t6;
          Grid[Prepend[SortBy[Last]@Transpose[funcs, timings], "function", "timing"],
          Dividers -> All]



          $beginarray
          hline
          textfunction & texttiming \
          hline
          textf4 & 0.0009 \
          hline
          textf6 & 0.0028 \
          hline
          textf1 & 0.003 \
          hline
          textf2 & 0.0034 \
          hline
          textf5 & 0.004 \
          hline
          textf3 & 0.012 \
          hline
          endarray$




          With na = 1000 we get




          $beginarray
          hline
          textfunction & texttiming \
          hline
          textf4 & 0.0014 \
          hline
          textf3 & 0.016 \
          hline
          textf2 & 0.0737 \
          hline
          textf6 & 0.117 \
          hline
          textf5 & 0.118 \
          hline
          textf1 & 0.59 \
          hline
          endarray$







          share|improve this answer











          $endgroup$








          • 3




            $begingroup$
            Cases[B, Alternatives@@A] is real-world poetry.
            $endgroup$
            – Roman
            May 4 at 6:12






          • 4




            $begingroup$
            +1. Also: SortBy[A, PositionIndex[B]]
            $endgroup$
            – WReach
            May 4 at 6:38






          • 2




            $begingroup$
            @WReach good idea to use an Association in SortBy. It's not in the documentation and looks very useful for future reference.
            $endgroup$
            – Roman
            May 4 at 12:52






          • 1




            $begingroup$
            Beautiful one-liners! I did not specify in my question but in my case, B only has unique elements. I have gone with the following solution: OrderLike[A_List,B_List]:=SortBy[A,FirstPosition[B,#]&]; I took out some of the syntactic sugar for us mere mortals.
            $endgroup$
            – c186282
            May 4 at 16:49






          • 1




            $begingroup$
            @c186282 it looks like you've chosen the slowest of all proposed methods. The one you picked has a runtime that scales quadratically with the lengths of the lists, whereas other methods scale linearly.
            $endgroup$
            – Roman
            May 4 at 18:44


















          6












          $begingroup$

          benchmarks



          No new methods here, only benchmarks of methods given in @kglr's answer.



          Clear[timings];
          timings[n_Integer] := timings[n] =
          Module[A, B, a1, a2, a3, a4, a5, a6, t1, t2, t3, t4, t5, t6,
          B = RandomSample[Range[n]];
          A = RandomSample[B, Floor[n/2]];
          t1 = First[AbsoluteTiming[a1 = SortBy[Position[B, #] &]@A;]];
          t2 = First[AbsoluteTiming[a2 = SortBy[A, FirstPosition[B, #] &];]];
          t3 = First[AbsoluteTiming[a3 = SortBy[PositionIndex@B]@A;]];
          t4 = First[AbsoluteTiming[a4 = Cases[Alternatives @@ A]@B;]];
          t5 = First[AbsoluteTiming[a5 = Select[MatchQ[Alternatives @@ A]]@B;]];
          t6 = First[AbsoluteTiming[a6 = DeleteCases[Except[Alternatives @@ A]]@B;]];
          If[a1 == a2 == a3 == a4 == a5 == a6, t1, t2, t3, t4, t5, t6, $Failed]]

          ListLogLogPlot[Transpose[Table[Thread[n, timings[n]],
          n, Round[10^Range[3, 9/2, 1/4]]]],
          Joined -> True, PlotLegends -> Range[6],
          Frame -> True, FrameLabel -> "n", "time [s]"]


          enter image description here



          Observations:



          • Methods 5 and 6 are almost indistinguishable in their timings.

          • Methods 3 & 4 scale linearly with $n$.

          • Methods 1, 2, 5, 6 scale quadratically with $n$.

          • Method 4 is the absolute front-runner: Cases[Alternatives @@ A]@B. Fast & poetic.





          share|improve this answer









          $endgroup$








          • 2




            $begingroup$
            Very nice I have changed my choise of method. I cannot miss out on fast and poetic.
            $endgroup$
            – c186282
            May 4 at 19:11






          • 1




            $begingroup$
            Always good to see visuals of benchmarks.
            $endgroup$
            – geordie
            May 6 at 12:48











          Your Answer








          StackExchange.ready(function()
          var channelOptions =
          tags: "".split(" "),
          id: "387"
          ;
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function()
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled)
          StackExchange.using("snippets", function()
          createEditor();
          );

          else
          createEditor();

          );

          function createEditor()
          StackExchange.prepareEditor(
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: false,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: null,
          bindNavPrevention: true,
          postfix: "",
          imageUploader:
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          ,
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          );



          );













          draft saved

          draft discarded


















          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmathematica.stackexchange.com%2fquestions%2f197648%2fselecting-elements-from-a-list-where-the-order-is-set-by-another-list%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown

























          2 Answers
          2






          active

          oldest

          votes








          2 Answers
          2






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          13












          $begingroup$

          SortBy[Position[B, #]&]@A



          2, 8, 5




          and



          SortBy[PositionIndex @ B] @ A (* thanks: WReach *)



          2, 8, 5




          Also,



          Cases[Alternatives @@ A] @ B
          Select[MatchQ[Alternatives @@ A]] @ B
          DeleteCases[Except[Alternatives @@ A]] @ B


          Update: Some timing comparisons:



          f1[a_, b_] := SortBy[FirstPosition[b, #] &]@a;
          f2[a_, b_] := SortBy[Position[b, #] &]@a;
          f3[a_, b_] := SortBy[PositionIndex @ b]@a;
          f4[a_, b_] := Cases[Alternatives @@ a] @ b;
          f5[a_, b_] := Select[MatchQ[Alternatives @@ a]] @ b;
          f6[a_, b_] := DeleteCases[Except[Alternatives @@ a]] @b;
          funcs = "f1", "f2", "f3", "f4", "f5", "f6";

          SeedRandom[1]
          nb = 10000;
          na = 5;
          b = RandomSample[Range[10^6], nb];
          a = RandomSample[b, na];
          t1 = First@RepeatedTiming[r1 = f1[a, b];];
          t2 = First@RepeatedTiming[r2 = f2[a, b];];
          t3 = First@RepeatedTiming[r3 = f3[a, b];];
          t4 = First@RepeatedTiming[r4 = f4[a, b];];
          t5 = First@RepeatedTiming[r5 = f5[a, b];];
          t6 = First@RepeatedTiming[r6 = f6[a, b];];
          r1 == r2 == r3 == r4 == r5 == r6



          True




          timings = t1, t2, t3, t4, t5, t6;
          Grid[Prepend[SortBy[Last]@Transpose[funcs, timings], "function", "timing"],
          Dividers -> All]



          $beginarray
          hline
          textfunction & texttiming \
          hline
          textf4 & 0.0009 \
          hline
          textf6 & 0.0028 \
          hline
          textf1 & 0.003 \
          hline
          textf2 & 0.0034 \
          hline
          textf5 & 0.004 \
          hline
          textf3 & 0.012 \
          hline
          endarray$




          With na = 1000 we get




          $beginarray
          hline
          textfunction & texttiming \
          hline
          textf4 & 0.0014 \
          hline
          textf3 & 0.016 \
          hline
          textf2 & 0.0737 \
          hline
          textf6 & 0.117 \
          hline
          textf5 & 0.118 \
          hline
          textf1 & 0.59 \
          hline
          endarray$







          share|improve this answer











          $endgroup$








          • 3




            $begingroup$
            Cases[B, Alternatives@@A] is real-world poetry.
            $endgroup$
            – Roman
            May 4 at 6:12






          • 4




            $begingroup$
            +1. Also: SortBy[A, PositionIndex[B]]
            $endgroup$
            – WReach
            May 4 at 6:38






          • 2




            $begingroup$
            @WReach good idea to use an Association in SortBy. It's not in the documentation and looks very useful for future reference.
            $endgroup$
            – Roman
            May 4 at 12:52






          • 1




            $begingroup$
            Beautiful one-liners! I did not specify in my question but in my case, B only has unique elements. I have gone with the following solution: OrderLike[A_List,B_List]:=SortBy[A,FirstPosition[B,#]&]; I took out some of the syntactic sugar for us mere mortals.
            $endgroup$
            – c186282
            May 4 at 16:49






          • 1




            $begingroup$
            @c186282 it looks like you've chosen the slowest of all proposed methods. The one you picked has a runtime that scales quadratically with the lengths of the lists, whereas other methods scale linearly.
            $endgroup$
            – Roman
            May 4 at 18:44















          13












          $begingroup$

          SortBy[Position[B, #]&]@A



          2, 8, 5




          and



          SortBy[PositionIndex @ B] @ A (* thanks: WReach *)



          2, 8, 5




          Also,



          Cases[Alternatives @@ A] @ B
          Select[MatchQ[Alternatives @@ A]] @ B
          DeleteCases[Except[Alternatives @@ A]] @ B


          Update: Some timing comparisons:



          f1[a_, b_] := SortBy[FirstPosition[b, #] &]@a;
          f2[a_, b_] := SortBy[Position[b, #] &]@a;
          f3[a_, b_] := SortBy[PositionIndex @ b]@a;
          f4[a_, b_] := Cases[Alternatives @@ a] @ b;
          f5[a_, b_] := Select[MatchQ[Alternatives @@ a]] @ b;
          f6[a_, b_] := DeleteCases[Except[Alternatives @@ a]] @b;
          funcs = "f1", "f2", "f3", "f4", "f5", "f6";

          SeedRandom[1]
          nb = 10000;
          na = 5;
          b = RandomSample[Range[10^6], nb];
          a = RandomSample[b, na];
          t1 = First@RepeatedTiming[r1 = f1[a, b];];
          t2 = First@RepeatedTiming[r2 = f2[a, b];];
          t3 = First@RepeatedTiming[r3 = f3[a, b];];
          t4 = First@RepeatedTiming[r4 = f4[a, b];];
          t5 = First@RepeatedTiming[r5 = f5[a, b];];
          t6 = First@RepeatedTiming[r6 = f6[a, b];];
          r1 == r2 == r3 == r4 == r5 == r6



          True




          timings = t1, t2, t3, t4, t5, t6;
          Grid[Prepend[SortBy[Last]@Transpose[funcs, timings], "function", "timing"],
          Dividers -> All]



          $beginarray
          hline
          textfunction & texttiming \
          hline
          textf4 & 0.0009 \
          hline
          textf6 & 0.0028 \
          hline
          textf1 & 0.003 \
          hline
          textf2 & 0.0034 \
          hline
          textf5 & 0.004 \
          hline
          textf3 & 0.012 \
          hline
          endarray$




          With na = 1000 we get




          $beginarray
          hline
          textfunction & texttiming \
          hline
          textf4 & 0.0014 \
          hline
          textf3 & 0.016 \
          hline
          textf2 & 0.0737 \
          hline
          textf6 & 0.117 \
          hline
          textf5 & 0.118 \
          hline
          textf1 & 0.59 \
          hline
          endarray$







          share|improve this answer











          $endgroup$








          • 3




            $begingroup$
            Cases[B, Alternatives@@A] is real-world poetry.
            $endgroup$
            – Roman
            May 4 at 6:12






          • 4




            $begingroup$
            +1. Also: SortBy[A, PositionIndex[B]]
            $endgroup$
            – WReach
            May 4 at 6:38






          • 2




            $begingroup$
            @WReach good idea to use an Association in SortBy. It's not in the documentation and looks very useful for future reference.
            $endgroup$
            – Roman
            May 4 at 12:52






          • 1




            $begingroup$
            Beautiful one-liners! I did not specify in my question but in my case, B only has unique elements. I have gone with the following solution: OrderLike[A_List,B_List]:=SortBy[A,FirstPosition[B,#]&]; I took out some of the syntactic sugar for us mere mortals.
            $endgroup$
            – c186282
            May 4 at 16:49






          • 1




            $begingroup$
            @c186282 it looks like you've chosen the slowest of all proposed methods. The one you picked has a runtime that scales quadratically with the lengths of the lists, whereas other methods scale linearly.
            $endgroup$
            – Roman
            May 4 at 18:44













          13












          13








          13





          $begingroup$

          SortBy[Position[B, #]&]@A



          2, 8, 5




          and



          SortBy[PositionIndex @ B] @ A (* thanks: WReach *)



          2, 8, 5




          Also,



          Cases[Alternatives @@ A] @ B
          Select[MatchQ[Alternatives @@ A]] @ B
          DeleteCases[Except[Alternatives @@ A]] @ B


          Update: Some timing comparisons:



          f1[a_, b_] := SortBy[FirstPosition[b, #] &]@a;
          f2[a_, b_] := SortBy[Position[b, #] &]@a;
          f3[a_, b_] := SortBy[PositionIndex @ b]@a;
          f4[a_, b_] := Cases[Alternatives @@ a] @ b;
          f5[a_, b_] := Select[MatchQ[Alternatives @@ a]] @ b;
          f6[a_, b_] := DeleteCases[Except[Alternatives @@ a]] @b;
          funcs = "f1", "f2", "f3", "f4", "f5", "f6";

          SeedRandom[1]
          nb = 10000;
          na = 5;
          b = RandomSample[Range[10^6], nb];
          a = RandomSample[b, na];
          t1 = First@RepeatedTiming[r1 = f1[a, b];];
          t2 = First@RepeatedTiming[r2 = f2[a, b];];
          t3 = First@RepeatedTiming[r3 = f3[a, b];];
          t4 = First@RepeatedTiming[r4 = f4[a, b];];
          t5 = First@RepeatedTiming[r5 = f5[a, b];];
          t6 = First@RepeatedTiming[r6 = f6[a, b];];
          r1 == r2 == r3 == r4 == r5 == r6



          True




          timings = t1, t2, t3, t4, t5, t6;
          Grid[Prepend[SortBy[Last]@Transpose[funcs, timings], "function", "timing"],
          Dividers -> All]



          $beginarray
          hline
          textfunction & texttiming \
          hline
          textf4 & 0.0009 \
          hline
          textf6 & 0.0028 \
          hline
          textf1 & 0.003 \
          hline
          textf2 & 0.0034 \
          hline
          textf5 & 0.004 \
          hline
          textf3 & 0.012 \
          hline
          endarray$




          With na = 1000 we get




          $beginarray
          hline
          textfunction & texttiming \
          hline
          textf4 & 0.0014 \
          hline
          textf3 & 0.016 \
          hline
          textf2 & 0.0737 \
          hline
          textf6 & 0.117 \
          hline
          textf5 & 0.118 \
          hline
          textf1 & 0.59 \
          hline
          endarray$







          share|improve this answer











          $endgroup$



          SortBy[Position[B, #]&]@A



          2, 8, 5




          and



          SortBy[PositionIndex @ B] @ A (* thanks: WReach *)



          2, 8, 5




          Also,



          Cases[Alternatives @@ A] @ B
          Select[MatchQ[Alternatives @@ A]] @ B
          DeleteCases[Except[Alternatives @@ A]] @ B


          Update: Some timing comparisons:



          f1[a_, b_] := SortBy[FirstPosition[b, #] &]@a;
          f2[a_, b_] := SortBy[Position[b, #] &]@a;
          f3[a_, b_] := SortBy[PositionIndex @ b]@a;
          f4[a_, b_] := Cases[Alternatives @@ a] @ b;
          f5[a_, b_] := Select[MatchQ[Alternatives @@ a]] @ b;
          f6[a_, b_] := DeleteCases[Except[Alternatives @@ a]] @b;
          funcs = "f1", "f2", "f3", "f4", "f5", "f6";

          SeedRandom[1]
          nb = 10000;
          na = 5;
          b = RandomSample[Range[10^6], nb];
          a = RandomSample[b, na];
          t1 = First@RepeatedTiming[r1 = f1[a, b];];
          t2 = First@RepeatedTiming[r2 = f2[a, b];];
          t3 = First@RepeatedTiming[r3 = f3[a, b];];
          t4 = First@RepeatedTiming[r4 = f4[a, b];];
          t5 = First@RepeatedTiming[r5 = f5[a, b];];
          t6 = First@RepeatedTiming[r6 = f6[a, b];];
          r1 == r2 == r3 == r4 == r5 == r6



          True




          timings = t1, t2, t3, t4, t5, t6;
          Grid[Prepend[SortBy[Last]@Transpose[funcs, timings], "function", "timing"],
          Dividers -> All]



          $beginarray
          hline
          textfunction & texttiming \
          hline
          textf4 & 0.0009 \
          hline
          textf6 & 0.0028 \
          hline
          textf1 & 0.003 \
          hline
          textf2 & 0.0034 \
          hline
          textf5 & 0.004 \
          hline
          textf3 & 0.012 \
          hline
          endarray$




          With na = 1000 we get




          $beginarray
          hline
          textfunction & texttiming \
          hline
          textf4 & 0.0014 \
          hline
          textf3 & 0.016 \
          hline
          textf2 & 0.0737 \
          hline
          textf6 & 0.117 \
          hline
          textf5 & 0.118 \
          hline
          textf1 & 0.59 \
          hline
          endarray$








          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited May 4 at 19:16

























          answered May 4 at 1:52









          kglrkglr

          192k10213433




          192k10213433







          • 3




            $begingroup$
            Cases[B, Alternatives@@A] is real-world poetry.
            $endgroup$
            – Roman
            May 4 at 6:12






          • 4




            $begingroup$
            +1. Also: SortBy[A, PositionIndex[B]]
            $endgroup$
            – WReach
            May 4 at 6:38






          • 2




            $begingroup$
            @WReach good idea to use an Association in SortBy. It's not in the documentation and looks very useful for future reference.
            $endgroup$
            – Roman
            May 4 at 12:52






          • 1




            $begingroup$
            Beautiful one-liners! I did not specify in my question but in my case, B only has unique elements. I have gone with the following solution: OrderLike[A_List,B_List]:=SortBy[A,FirstPosition[B,#]&]; I took out some of the syntactic sugar for us mere mortals.
            $endgroup$
            – c186282
            May 4 at 16:49






          • 1




            $begingroup$
            @c186282 it looks like you've chosen the slowest of all proposed methods. The one you picked has a runtime that scales quadratically with the lengths of the lists, whereas other methods scale linearly.
            $endgroup$
            – Roman
            May 4 at 18:44












          • 3




            $begingroup$
            Cases[B, Alternatives@@A] is real-world poetry.
            $endgroup$
            – Roman
            May 4 at 6:12






          • 4




            $begingroup$
            +1. Also: SortBy[A, PositionIndex[B]]
            $endgroup$
            – WReach
            May 4 at 6:38






          • 2




            $begingroup$
            @WReach good idea to use an Association in SortBy. It's not in the documentation and looks very useful for future reference.
            $endgroup$
            – Roman
            May 4 at 12:52






          • 1




            $begingroup$
            Beautiful one-liners! I did not specify in my question but in my case, B only has unique elements. I have gone with the following solution: OrderLike[A_List,B_List]:=SortBy[A,FirstPosition[B,#]&]; I took out some of the syntactic sugar for us mere mortals.
            $endgroup$
            – c186282
            May 4 at 16:49






          • 1




            $begingroup$
            @c186282 it looks like you've chosen the slowest of all proposed methods. The one you picked has a runtime that scales quadratically with the lengths of the lists, whereas other methods scale linearly.
            $endgroup$
            – Roman
            May 4 at 18:44







          3




          3




          $begingroup$
          Cases[B, Alternatives@@A] is real-world poetry.
          $endgroup$
          – Roman
          May 4 at 6:12




          $begingroup$
          Cases[B, Alternatives@@A] is real-world poetry.
          $endgroup$
          – Roman
          May 4 at 6:12




          4




          4




          $begingroup$
          +1. Also: SortBy[A, PositionIndex[B]]
          $endgroup$
          – WReach
          May 4 at 6:38




          $begingroup$
          +1. Also: SortBy[A, PositionIndex[B]]
          $endgroup$
          – WReach
          May 4 at 6:38




          2




          2




          $begingroup$
          @WReach good idea to use an Association in SortBy. It's not in the documentation and looks very useful for future reference.
          $endgroup$
          – Roman
          May 4 at 12:52




          $begingroup$
          @WReach good idea to use an Association in SortBy. It's not in the documentation and looks very useful for future reference.
          $endgroup$
          – Roman
          May 4 at 12:52




          1




          1




          $begingroup$
          Beautiful one-liners! I did not specify in my question but in my case, B only has unique elements. I have gone with the following solution: OrderLike[A_List,B_List]:=SortBy[A,FirstPosition[B,#]&]; I took out some of the syntactic sugar for us mere mortals.
          $endgroup$
          – c186282
          May 4 at 16:49




          $begingroup$
          Beautiful one-liners! I did not specify in my question but in my case, B only has unique elements. I have gone with the following solution: OrderLike[A_List,B_List]:=SortBy[A,FirstPosition[B,#]&]; I took out some of the syntactic sugar for us mere mortals.
          $endgroup$
          – c186282
          May 4 at 16:49




          1




          1




          $begingroup$
          @c186282 it looks like you've chosen the slowest of all proposed methods. The one you picked has a runtime that scales quadratically with the lengths of the lists, whereas other methods scale linearly.
          $endgroup$
          – Roman
          May 4 at 18:44




          $begingroup$
          @c186282 it looks like you've chosen the slowest of all proposed methods. The one you picked has a runtime that scales quadratically with the lengths of the lists, whereas other methods scale linearly.
          $endgroup$
          – Roman
          May 4 at 18:44











          6












          $begingroup$

          benchmarks



          No new methods here, only benchmarks of methods given in @kglr's answer.



          Clear[timings];
          timings[n_Integer] := timings[n] =
          Module[A, B, a1, a2, a3, a4, a5, a6, t1, t2, t3, t4, t5, t6,
          B = RandomSample[Range[n]];
          A = RandomSample[B, Floor[n/2]];
          t1 = First[AbsoluteTiming[a1 = SortBy[Position[B, #] &]@A;]];
          t2 = First[AbsoluteTiming[a2 = SortBy[A, FirstPosition[B, #] &];]];
          t3 = First[AbsoluteTiming[a3 = SortBy[PositionIndex@B]@A;]];
          t4 = First[AbsoluteTiming[a4 = Cases[Alternatives @@ A]@B;]];
          t5 = First[AbsoluteTiming[a5 = Select[MatchQ[Alternatives @@ A]]@B;]];
          t6 = First[AbsoluteTiming[a6 = DeleteCases[Except[Alternatives @@ A]]@B;]];
          If[a1 == a2 == a3 == a4 == a5 == a6, t1, t2, t3, t4, t5, t6, $Failed]]

          ListLogLogPlot[Transpose[Table[Thread[n, timings[n]],
          n, Round[10^Range[3, 9/2, 1/4]]]],
          Joined -> True, PlotLegends -> Range[6],
          Frame -> True, FrameLabel -> "n", "time [s]"]


          enter image description here



          Observations:



          • Methods 5 and 6 are almost indistinguishable in their timings.

          • Methods 3 & 4 scale linearly with $n$.

          • Methods 1, 2, 5, 6 scale quadratically with $n$.

          • Method 4 is the absolute front-runner: Cases[Alternatives @@ A]@B. Fast & poetic.





          share|improve this answer









          $endgroup$








          • 2




            $begingroup$
            Very nice I have changed my choise of method. I cannot miss out on fast and poetic.
            $endgroup$
            – c186282
            May 4 at 19:11






          • 1




            $begingroup$
            Always good to see visuals of benchmarks.
            $endgroup$
            – geordie
            May 6 at 12:48















          6












          $begingroup$

          benchmarks



          No new methods here, only benchmarks of methods given in @kglr's answer.



          Clear[timings];
          timings[n_Integer] := timings[n] =
          Module[A, B, a1, a2, a3, a4, a5, a6, t1, t2, t3, t4, t5, t6,
          B = RandomSample[Range[n]];
          A = RandomSample[B, Floor[n/2]];
          t1 = First[AbsoluteTiming[a1 = SortBy[Position[B, #] &]@A;]];
          t2 = First[AbsoluteTiming[a2 = SortBy[A, FirstPosition[B, #] &];]];
          t3 = First[AbsoluteTiming[a3 = SortBy[PositionIndex@B]@A;]];
          t4 = First[AbsoluteTiming[a4 = Cases[Alternatives @@ A]@B;]];
          t5 = First[AbsoluteTiming[a5 = Select[MatchQ[Alternatives @@ A]]@B;]];
          t6 = First[AbsoluteTiming[a6 = DeleteCases[Except[Alternatives @@ A]]@B;]];
          If[a1 == a2 == a3 == a4 == a5 == a6, t1, t2, t3, t4, t5, t6, $Failed]]

          ListLogLogPlot[Transpose[Table[Thread[n, timings[n]],
          n, Round[10^Range[3, 9/2, 1/4]]]],
          Joined -> True, PlotLegends -> Range[6],
          Frame -> True, FrameLabel -> "n", "time [s]"]


          enter image description here



          Observations:



          • Methods 5 and 6 are almost indistinguishable in their timings.

          • Methods 3 & 4 scale linearly with $n$.

          • Methods 1, 2, 5, 6 scale quadratically with $n$.

          • Method 4 is the absolute front-runner: Cases[Alternatives @@ A]@B. Fast & poetic.





          share|improve this answer









          $endgroup$








          • 2




            $begingroup$
            Very nice I have changed my choise of method. I cannot miss out on fast and poetic.
            $endgroup$
            – c186282
            May 4 at 19:11






          • 1




            $begingroup$
            Always good to see visuals of benchmarks.
            $endgroup$
            – geordie
            May 6 at 12:48













          6












          6








          6





          $begingroup$

          benchmarks



          No new methods here, only benchmarks of methods given in @kglr's answer.



          Clear[timings];
          timings[n_Integer] := timings[n] =
          Module[A, B, a1, a2, a3, a4, a5, a6, t1, t2, t3, t4, t5, t6,
          B = RandomSample[Range[n]];
          A = RandomSample[B, Floor[n/2]];
          t1 = First[AbsoluteTiming[a1 = SortBy[Position[B, #] &]@A;]];
          t2 = First[AbsoluteTiming[a2 = SortBy[A, FirstPosition[B, #] &];]];
          t3 = First[AbsoluteTiming[a3 = SortBy[PositionIndex@B]@A;]];
          t4 = First[AbsoluteTiming[a4 = Cases[Alternatives @@ A]@B;]];
          t5 = First[AbsoluteTiming[a5 = Select[MatchQ[Alternatives @@ A]]@B;]];
          t6 = First[AbsoluteTiming[a6 = DeleteCases[Except[Alternatives @@ A]]@B;]];
          If[a1 == a2 == a3 == a4 == a5 == a6, t1, t2, t3, t4, t5, t6, $Failed]]

          ListLogLogPlot[Transpose[Table[Thread[n, timings[n]],
          n, Round[10^Range[3, 9/2, 1/4]]]],
          Joined -> True, PlotLegends -> Range[6],
          Frame -> True, FrameLabel -> "n", "time [s]"]


          enter image description here



          Observations:



          • Methods 5 and 6 are almost indistinguishable in their timings.

          • Methods 3 & 4 scale linearly with $n$.

          • Methods 1, 2, 5, 6 scale quadratically with $n$.

          • Method 4 is the absolute front-runner: Cases[Alternatives @@ A]@B. Fast & poetic.





          share|improve this answer









          $endgroup$



          benchmarks



          No new methods here, only benchmarks of methods given in @kglr's answer.



          Clear[timings];
          timings[n_Integer] := timings[n] =
          Module[A, B, a1, a2, a3, a4, a5, a6, t1, t2, t3, t4, t5, t6,
          B = RandomSample[Range[n]];
          A = RandomSample[B, Floor[n/2]];
          t1 = First[AbsoluteTiming[a1 = SortBy[Position[B, #] &]@A;]];
          t2 = First[AbsoluteTiming[a2 = SortBy[A, FirstPosition[B, #] &];]];
          t3 = First[AbsoluteTiming[a3 = SortBy[PositionIndex@B]@A;]];
          t4 = First[AbsoluteTiming[a4 = Cases[Alternatives @@ A]@B;]];
          t5 = First[AbsoluteTiming[a5 = Select[MatchQ[Alternatives @@ A]]@B;]];
          t6 = First[AbsoluteTiming[a6 = DeleteCases[Except[Alternatives @@ A]]@B;]];
          If[a1 == a2 == a3 == a4 == a5 == a6, t1, t2, t3, t4, t5, t6, $Failed]]

          ListLogLogPlot[Transpose[Table[Thread[n, timings[n]],
          n, Round[10^Range[3, 9/2, 1/4]]]],
          Joined -> True, PlotLegends -> Range[6],
          Frame -> True, FrameLabel -> "n", "time [s]"]


          enter image description here



          Observations:



          • Methods 5 and 6 are almost indistinguishable in their timings.

          • Methods 3 & 4 scale linearly with $n$.

          • Methods 1, 2, 5, 6 scale quadratically with $n$.

          • Method 4 is the absolute front-runner: Cases[Alternatives @@ A]@B. Fast & poetic.






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered May 4 at 18:56









          RomanRoman

          8,20311238




          8,20311238







          • 2




            $begingroup$
            Very nice I have changed my choise of method. I cannot miss out on fast and poetic.
            $endgroup$
            – c186282
            May 4 at 19:11






          • 1




            $begingroup$
            Always good to see visuals of benchmarks.
            $endgroup$
            – geordie
            May 6 at 12:48












          • 2




            $begingroup$
            Very nice I have changed my choise of method. I cannot miss out on fast and poetic.
            $endgroup$
            – c186282
            May 4 at 19:11






          • 1




            $begingroup$
            Always good to see visuals of benchmarks.
            $endgroup$
            – geordie
            May 6 at 12:48







          2




          2




          $begingroup$
          Very nice I have changed my choise of method. I cannot miss out on fast and poetic.
          $endgroup$
          – c186282
          May 4 at 19:11




          $begingroup$
          Very nice I have changed my choise of method. I cannot miss out on fast and poetic.
          $endgroup$
          – c186282
          May 4 at 19:11




          1




          1




          $begingroup$
          Always good to see visuals of benchmarks.
          $endgroup$
          – geordie
          May 6 at 12:48




          $begingroup$
          Always good to see visuals of benchmarks.
          $endgroup$
          – geordie
          May 6 at 12:48

















          draft saved

          draft discarded
















































          Thanks for contributing an answer to Mathematica Stack Exchange!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid


          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.

          Use MathJax to format equations. MathJax reference.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmathematica.stackexchange.com%2fquestions%2f197648%2fselecting-elements-from-a-list-where-the-order-is-set-by-another-list%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          How to write a 12-bar blues melodyI-IV-V blues progressionHow to play the bridges in a standard blues progressionHow does Gdim7 fit in C# minor?question on a certain chord progressionMusicology of Melody12 bar blues, spread rhythm: alternative to 6th chord to avoid finger stretchChord progressions/ Root key/ MelodiesHow to put chords (POP-EDM) under a given lead vocal melody (starting from a good knowledge in music theory)Are there “rules” for improvising with the minor pentatonic scale over 12-bar shuffle?Confusion about blues scale and chords

          What if the end-user didn't have the required library?What is setup.py?What is a clean, pythonic way to have multiple constructors in Python?What does Ruby have that Python doesn't, and vice versa?What is the reason for having '//' in Python?How do I create a namespace package in Python?How to package shared objects that python modules depend on?setuptools vs. distutils: why is distutils still a thing?Navigation in Windows 10 vs code not going to virtualenv library when the same library is installed at user levelPython create package for local usePackaging a project that uses multiple python versionsWhy is permission denied on pip install except for when “--user” is included at end of command?

          Why did Thanos need his ship to help him in the battle scene?Which actor plays Thanos in the Avengers mid-credits scene?Are there economic implications portrayed in comics where the buildings and cities are ruined almost daily?Old X-Men comic where team travels to alien world with a ring-like sun that needs recharging?Why does Ego need help sleeping?Is there an objective answer to who “the strongest Avenger” is?How did Banner get unstuck?Why did Thanos get hit?How did Thanos (or anyone) know the Infinity Stones would give him this power?Did Thanos leave Eitri alive for his after-sales service?In Avengers 1, why does Thanos need Loki?