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.
$\begingroup$
$\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$– Dr. belisariusCommented Dec 30, 2014 at 19:49
Add a comment
|
2 Answers
$\begingroup$
$\endgroup$
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
*)
$\begingroup$
$\endgroup$
2
Alternately,
Total@((#[[1]][#[[2]]] &) /@ Tuples[{##}]) &[(Function[v,
Function[u, Length@Select[u, # == v &]]] /@ {"11", "12",
"13"}), {{"11", "12", "13", "14"}}]
-
$\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$– VerbeiaCommented Dec 31, 2014 at 1:35 -