4
$\begingroup$

I have a list of some sort list = {"l1","l2","l3","l4"} and I'd like to count the sum total number of occurrences of n of the elements in the list. This is easily done for one element: Count[list, "l1"] which gives 1. How can I write something like Count[list, "l3" OR "l2" OR "l1"], in this example giving the output 3? I read through the manual for Count and surprisingly couldn't find out how to ask for this.

$\endgroup$
1
  • $\begingroup$ Welcome to Mathematica.SE! I suggest the following: 1) As you receive help, try to give it too, by answering questions in your area of expertise. 2) Read the faq! 3) When you see good questions and answers, vote them up by clicking the gray triangles, because the credibility of the system is based on the reputation gained by users sharing their knowledge. Also, please remember to accept the answer, if any, that solves your problem, by clicking the checkmark sign! $\endgroup$ Commented Dec 30, 2014 at 19:49

2 Answers 2

4
$\begingroup$

Use Alternatives. You aren't getting any help from the Count[] docs because it's more related to Patterns

list = {"l1", "l2", "l3", "l4"};
Count[list, Alternatives["l1", "l2", "l3"]]
(* or abbreviated *)
Count[list, "l1" | "l2" | "l3"]
(*
 3
 3
*)
$\endgroup$
1
$\begingroup$

Alternately,

Total@((#[[1]][#[[2]]] &) /@ Tuples[{##}]) &[(Function[v, 
Function[u, Length@Select[u, # == v &]]] /@ {"11", "12", 
"13"}), {{"11", "12", "13", "14"}}]
$\endgroup$
2
  • $\begingroup$ This gives the right result for the test case, but isn't it a bit convoluted compared with the built-in Alternatives function? $\endgroup$
    – Verbeia
    Commented Dec 31, 2014 at 1:35
  • $\begingroup$ Yes, very much. $\endgroup$ Commented Dec 31, 2014 at 1:55

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.