1
$\begingroup$

I want to make a selection on this list

words = {{{"word1", "word2"}, 19}, {{"word1", "word3"}, 
   8}, {{"word1", "word4"}, 7}, {{"word2", "word5"}, 
   7}, {{"word2", "word5"}, 7}, {{"word3", "word6"}, 
   7}, {{"word3", "word7"}, 7}, {{"word3", "word8"}, 
   6}, {{"word4", "word6"}, 6}};

From this list, I want to select all 'records' which have one of these words

wordsselect = {"word2", "word4", "word8"}

The desirde output is:

wordsnew = {{{"word1", "word2"}, 19}, {{"word1", "word4"}, 
   7}, {{"word2", "word5"}, 7}, {{"word2", "word5"}, 
   7}, {{"word3", "word8"}, 6}, {{"word4", "word6"}, 6}}

I tried to make a selection based on one word

Select[words[[All, {1, 2}]], MemberQ[#[[1]], "word2"] &]

this works fine. So I tried the next script

Select[words[[All, {1, 2}]], MemberQ[#[[1]], wordsselect ] &]

The output is empty {}

I have two questions:

  1. How do I get the desired output?

  2. Why is my second try not working?

$\endgroup$
  • 6
    $\begingroup$ Try Alternatives@@wordsselect instead. This will be a real pattern involving alternatives. Your pattern matches with any list that exactly equals the list of three words. $\endgroup$ – Sjoerd C. de Vries Jul 13 '15 at 20:59
3
$\begingroup$

As already noted the second argument of MemberQ needs to be a pattern or literal expression; Alternatives can be used here.

Another method is to use IntersectingQ instead:

Select[words, IntersectingQ[#[[1]], wordsselect] &]
{{{"word1", "word2"}, 19}, {{"word1", "word4"}, 7},
 {{"word2", "word5"}, 7}, {{"word2", "word5"}, 7},
 {{"word3", "word8"}, 6}, {{"word4", "word6"}, 6}}
$\endgroup$
  • $\begingroup$ thank you again finding yet another useful function I was not aware of: IntersectingQ...my blindspot seems ever increasing as my time is ever decreasing...+1 :) $\endgroup$ – ubpdqn Jul 14 '15 at 12:55
1
$\begingroup$
Select[words, MemberQ[#[[1]], "word1" | "word2" | "word8"] &]
$\endgroup$
1
$\begingroup$
  1. This one should work:

Select[words, Or @@ (MemberQ[wordsselect, #] & /@ #[[1]]) &]

It checks for each one of the words in the first list-element. If there is at least one word in the wordsselect list then the whole element is selected.

  1. With MemberQ[#[[1]], wordsselect ] & you are checking if the list wordsselect is inside each {"wordX","wordY"}
$\endgroup$
0
$\begingroup$

Just for something different:

Flatten[Last@Reap[Sow[{##}, #1] & @@@ words, wordsselect, #2 &], 2]
$\endgroup$
0
$\begingroup$

Pre v10 without IntersectingQ you can do this:

 Select[words, Length@Intersection[#[[1]], wordsselect] > 0 &]
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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