在1行代码中计算向量中每个唯一整数的实例? [英] Count instances of each unique integer in a vector in 1 line of code?
本文介绍了在1行代码中计算向量中每个唯一整数的实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否有一种巧妙的方法可以重写此Julia函数(也许仅使用一行代码)而又不会使其变慢呢? (我刚开始使用Julia.这太棒了!)K
是一个正整数,而zd
是一个不大于K
的正整数向量.谢谢!
Is there a slick way to rewrite this Julia function, perhaps using just 1 line of code, without making it much slower? (I just started using Julia. It's great!) K
is a positive integer and zd
is a vector of positive integers no greater than K
. Thanks!
function tally(zd)
ret = zeros(Int64, K)
for k in zd
ret[k] += 1
end
return ret
end
示例:
julia> K = 5
julia> zd = [1,2,2,2,2,3];
julia> tally(zd)
5-element Array{Float64,1}:
1
4
1
0
0
推荐答案
我尚未测试性能,但是使用hist函数应该可以:
I haven't tested the performance, but using the hist function should work:
hist(zd,0.5:K+0.5)[2]
给予:
5元素数组{Int64,1}: 1个 4 1个 0 0
5-element Array{Int64,1}: 1 4 1 0 0
或者,如果零不重要,则只需使用
or, if the zeros are unimportant, just use
hist(zd)[2]
3-element Array{Int64,1}:
1
4
1
这篇关于在1行代码中计算向量中每个唯一整数的实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文