Select using MemberQ

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:

How do I get the desired output?
Why is my second try not working?

=================

6

 

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.
– Sjoerd C. de Vries
Jul 13 ’15 at 20:59

=================

5 Answers
5

=================

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}}

  

 

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 🙂
– ubpdqn
Jul 14 ’15 at 12:55

Select[words, MemberQ[#[[1]], “word1” | “word2” | “word8”] &]

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.

With MemberQ[#[[1]], wordsselect ] & you are checking if the list wordsselect is inside each {“wordX”,”wordY”}

Just for something different:

Flatten[Last@Reap[Sow[{##}, #1] & @@@ words, wordsselect, #2 &], 2]

Pre v10 without IntersectingQ you can do this:

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