计算与谓词匹配的元素数量的惯用方法是什么? [英] What is the idiomatic way of counting the number of elements matching predicate?
本文介绍了计算与谓词匹配的元素数量的惯用方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
除此之外,是否有更好的方法来计算谓词函数为真的元素的数量:
Is there a better way to count the number of elements for which the predicate function is true, other than this:
PredCount[lst_, pred_] := Length@Select[lst, pred];
我之所以这么问是因为用 Select[]
构建 lst
的子集似乎效率低下,而且因为 Count[]
只能工作有图案.在我的用例中,函数 PredCount
被多次调用,lst
很大.
I'm asking because it seems inefficient to construct a subset of lst
with Select[]
, and because Count[]
only works with patterns. In my use case, the function PredCount
is called many times with a large lst
.
推荐答案
通常可以通过将谓词转换为带条件的模式来实现.例如:
You can often do this by turning your predicate into a pattern with a condition. For example:
Count[list, x_/;x>5]
将计算列表中大于 5 的元素数.
would count the number of elements in list which are greater than 5.
这篇关于计算与谓词匹配的元素数量的惯用方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文