在 Julia 中计算数组中元素的数量 – count() 方法
count()
是 julia 中的内置函数,用于计算给定谓词 p 返回 true 的指定数组中的元素数,如果省略 p,则计算给定布尔值集合中的真实元素数.
Syntax:
count(p, itr)
or
count(itr)
Parameters:
- p: Specified set of instructions.
- itr: Specified collection of boolean values.
Returns: It returns the count of the number of elements in the specified array for which the given predicate p returns true and if p is omitted, counts the number of true elements in the given collection of boolean values.
示例 1:
# Julia program to illustrate
# the use of count() method
# Getting the count of the number
# of elements in the specified array
# for which the given predicate p
# returns true.
println(count(i->(i<= 3), [1, 2, 3, 4, 5]))
println(count(i->(i>3), [1, 2, 3, 4, 5]))
println(count(i->(2<= i<= 5), [1, 2, 3, 4, 5]))
println(count(i->(i>= 0), [1, 2, 3]))
输出:
3
2
4
3
示例 2:
# Julia program to illustrate
# the use of count() method
# Getting the counts of number of true elements
# in the given collection of boolean values.
println(count([false, false, false]))
println(count([true, false, true]))
println(count([true, true, true]))
输出:
0
2
3