Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

I was trying to make this

L1 = {{2, 1}, {6, 4}, {8, 7}, {9, 5}};
L2 = {{2, 9}, {9, 6}};
L = Union[L2 , L1]

And I used this:

Cases[L, {{a_, _}, {b_, _}} /; a == b]
Complement[L,L2]

And this:

DeleteCases[L, MemberQ[L1, {#[[1]], _}] & /@ L2]

But, both fail. The answer must take from L1 only the elements where the first element appear in L2. For L1 and L2 above, must return

{{2,1},{9,5}} 

And {6, 4} and {8, 7} must be dropped from L2!

Thanks,

share|improve this question

2 Answers 2

up vote 4 down vote accepted

Using Cases:

L1 = {{2, 1}, {6, 4}, {8, 7}, {9, 5}};
L2 = {{2, 9}, {9, 6}};

With[{a = Alternatives @@ L2[[All, 1]]}, Cases[L1, {a, _}]]
share|improve this answer
    
And the complement to your answer: With[{a = Alternatives @@ L2[[All, 1]]}, DeleteCases[L1, {Except@a, _}]] :) –  rm -rf Dec 17 '13 at 20:40
    
Simon, why use With here? Clarity? –  Mr.Wizard Dec 18 '13 at 0:59
    
@Mr.Wizard, yes, just for clarity. Not really necessary here, but I did some work recently with rather complex string patterns and got into the habit of doing this to make StringCases and StringMatchQ expressions more readable. –  Simon Woods Dec 18 '13 at 9:46
    
Okay, just checking. I sometimes use Function the same way, e.g. Alternatives @@ L2[[All, 1]] // Cases[L1, {#, _}] &. –  Mr.Wizard Dec 18 '13 at 9:49
    
Could you tell me if I am wrong: the command With will take the cases in L1 where a could be any of the first elements in the list L2 (2 and 9 for this example)...it is ok? –  Jotasmall Dec 18 '13 at 17:34
L1 = {{2, 1}, {6, 4}, {8, 7}, {9, 5}};
L2 = {{2, 9}, {9, 6}};
Select[L1, MemberQ[L2[[All, 1]], First@#] &]
(*
{{2, 1}, {9, 5}}
*)
share|improve this answer
    
This will reevaluate L2[[All, 1]] for every element of L1. This is not ideal for long lists. –  Mr.Wizard Dec 18 '13 at 1:01
    
@Mr.Wizard ` When deciding whether to optimize a specific part of the program, Amdahl's Law should always be considered: the impact on the overall program depends very much on how much time is actually spent in that specific part, which is not always clear from looking at the code without a performance analysis.` –  belisarius Dec 18 '13 at 1:37

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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