What is the idiomatic way of counting the number of elements matching predicate?

廉价感情. 提交于 2019-12-10 21:33:32

问题


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];

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.


回答1:


You can often do this by turning your predicate into a pattern with a condition. For example:

Count[list, x_/;x>5]

would count the number of elements in list which are greater than 5.




回答2:


I would use PatternTest

PredCount = Count[#, _?#2] &;

PredCount[Range@30, PrimeQ]
(*out*) 10

This pattern is simple enough that you might use Count directly.



来源:https://stackoverflow.com/questions/10344339/what-is-the-idiomatic-way-of-counting-the-number-of-elements-matching-predicate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!