I have the following matrix:

l = {{{"black_pepper", "cabbage", "carrot", "cumin", "olive_oil", 
 "onion", "potato", "TURMERIC"}, {"bell_pepper", "cayenne", 
 "cilantro", "cumin", "garlic", "lemon_juice", "olive_oil", 
 "parsley"}, {"butter", "cayenne", "coconut", "onion", 
 "roasted_peanut", "tomato", "vegetable_oil", "vinegar"}}};

I am trying to select the element that has "TURMERIC" in it. So the output should be the first element of l. I tried:

Select[l, StringContainsQ@# == "TURMERIC" &]

but it returns empty list. What am I doing wrong here?

  • $\begingroup$ You have a list of lists of strings, so you need a selection function that acts on a list. Try Select[l, MemberQ[#, StringContainsQ[#, "TURMERIC"] &] &]. (Can't test since I only have gedanken Mathematica currently.) $\endgroup$ – J. M.'s ennui Oct 9 '18 at 15:52
  • $\begingroup$ @J.M.issomewhatokay. Thanks but when I run your code, it returns empty list as well. $\endgroup$ – Wiliam Oct 9 '18 at 15:54
  • $\begingroup$ Hmm, sorry; try this instead: Select[l, MemberQ[#, s_String /; StringContainsQ[s, "TURMERIC"]] &] $\endgroup$ – J. M.'s ennui Oct 9 '18 at 15:55
  • $\begingroup$ Select[Catenate@l, MemberQ[#, "TURMERIC"] &] or Select[Catenate@l, MemberQ[#, "TURMERIC"] &]//Flatten (or Cases[l, {___, "TURMERIC", ___}, -1]) $\endgroup$ – user1066 Oct 9 '18 at 19:39

There is a somewhat superfluous first level in l, so we map the operator form of select over it. Moreover, we just need MemberQ, not StringContainsQ, no?

Select[MemberQ["TURMERIC"]] /@ l

{{{"black_pepper", "cabbage", "carrot", "cumin", "olive_oil", "onion", "potato", "TURMERIC"}}}

  • $\begingroup$ Thanks Select[l, MemberQ[#, s_String /; StringContainsQ[s, "TURMERIC"]] &] works if there is no {{{. I need the out put to be the whole element though. If you read the question, I have said I needed the elements to be in the format: {"black_pepper", "cabbage", "carrot", "cumin", "olive_oil", "onion", "potato", "TURMERIC"} $\endgroup$ – Wiliam Oct 9 '18 at 16:04

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.