1
$\begingroup$

This is a followup question to this one.

Let a and b be lists of lists like this:

a= {{"apples", "pears", 1, 17},
{"pineapples", "apples", 5, 7},
{"yes", "building", 4, 7},
{"no","camel","rabbit",0}}
  
b= {{"man", 1, 2, 17},
{"pineapples", "apples", "cow", "yes"},
{"no","camel","carpet","wibble"},
{"yes", "buildings", 4, 7}}

How can I remove from b every row that doesn't share both its 1st and its 2nd elements, say, in that order and in those specific slots, with any of the rows in a?

Once they've been deleted in this example, b would become

 b= { {"pineapples", "apples", "cow", "yes"},
{"no","camel","carpet","wibble"}}

As far as I can tell, ∈ can't be used to define a criterion in Cases.

$\endgroup$
4
  • 1
    $\begingroup$ Maybe Select[b, ! FreeQ[a[[All, 1 ;; 2]], #[[1 ;; 2]]] &] $\endgroup$
    – vindobona
    Oct 23, 2023 at 18:50
  • $\begingroup$ Thanks, but that only picks up the "pineapples" element and misses the "no" one. $\endgroup$
    – tell
    Oct 23, 2023 at 19:24
  • $\begingroup$ I guess that's because the comma is missing after the 3rd element in the definition of b $\endgroup$
    – vindobona
    Oct 23, 2023 at 19:27
  • 1
    $\begingroup$ Ah yes. You are right! It works fine now. $\endgroup$
    – tell
    Oct 23, 2023 at 19:28

4 Answers 4

2
$\begingroup$
Select[b, MemberQ[a[[All, {1, 2}]], #[[{1, 2}]]] &]
$\endgroup$
1
  • $\begingroup$ Yes. Got it. This works fine now, as also does @vindobona's suggestion. Many thanks! $\endgroup$
    – tell
    Oct 23, 2023 at 19:29
2
$\begingroup$
Intersection[b, a, SameTest -> (#[[;; 2]] == #2[[;; 2]] &)]
{{"no", "camel", "carpet", "wibble"},   
 {"pineapples", "apples", "cow", "yes"}}
$\endgroup$
0
$\begingroup$
Cases[{a_, _} :> Flatten @ a] @
 GatherBy[MapApply[{{#1, #2}, {##3}} &] @ Join[b, a], First]

{{"pineapples", "apples", "cow", "yes"}, {"no", "camel", "carpet", "wibble"}}

$\endgroup$
0
$\begingroup$
a = {{"apples", "pears", 1, 17}, {"pineapples", "apples", 5, 
   7}, {"yes", "building", 4, 7}, {"no", "camel", "rabbit", 0}}
b = {{"man", 1, 2, 17}, {"pineapples", "apples", "cow", "yes"}, {"no",
    "camel", "carpet", "wibble"}, {"yes", "buildings", 4, 7}}

d1 = #[[1 ;; 2]] -> #[[3 ;;]] & /@ a;
d2 = #[[1 ;; 2]] -> #[[3 ;;]] & /@ b;

KeySelect[d2, KeyMemberQ[d1, #] &] // KeyValueMap[Flatten@*List]

{{"pineapples", "apples", "cow", "yes"}, {"no", "camel", "carpet",
"wibble"}}

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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