在 1 行代码中计算向量中每个唯一整数的实例? [英] Count instances of each unique integer in a vector in 1 line of code?

查看:10
本文介绍了在 1 行代码中计算向量中每个唯一整数的实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种巧妙的方法来重写这个 Julia 函数,也许只使用 1 行代码,而不会使它变得更慢?(我刚开始使用 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}:14100

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆