1
$\begingroup$

Suppose we have the following list:

l={{"a"}, {"a", "d"}, {"a", "d"}, {"a", "b"}, {"a", "b", "d"}, {"a", 
  "b", "c"}, {"a", "c", "d"}, {"a", "b", "d"}, {"a", "d"}, {"b", "d"}}

I want to count those entries that have "a","d" in them, I tried the following:

Select[l, # == {"a", "d"} &] // Length

which gives 3, yet there are other entries that have "a" and "d" in them and the output must be,

{{"a", "d"}, {"a", "d"}, {"a", "b", "d"}, {"a", "c", "d"}, {"a", "b", "d"}, {"a", "d"}}

which has length 6. How does one solve this?

$\endgroup$
  • 1
    $\begingroup$ Select[l, ContainsAll[{"a", "d"}]] $\endgroup$ – MarcoB Mar 19 at 13:23
  • $\begingroup$ @MarcoB Thank you $\endgroup$ – William Mar 19 at 13:24
2
$\begingroup$

You could use either of the following with Length:

Select[l, ContainsAll[{"a", "d"}]]

Cases[l, {___, "a", ___, "d", ___}]

Alternatively, if all you care is the number of occurrences, and not the occurrences themselves, you could use Count:

Count[l, {___, "a", ___, "d", ___}]
$\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.