Python 如何在Julia中组合countmap和proportionmap?

Python 如何在Julia中组合countmap和proportionmap?,python,counter,julia,Python,Counter,Julia,可以整理列表中的项目计数: import StatsBase: countmap, proportionmap, addcounts! a = [1,2,3,4,1,2,2,3,1,2,5,7,4,8,4] b = [1,2,5,3,1,6,1,6,1,2,6,2] x, y = countmap(a), countmap(b) [out]: (Dict(7=>1,4=>3,2=>4,3=>2,5=>1,8=>1,1=>3),Dict(2=>3,

可以整理列表中的项目计数:

import StatsBase: countmap, proportionmap, addcounts!
a = [1,2,3,4,1,2,2,3,1,2,5,7,4,8,4]
b = [1,2,5,3,1,6,1,6,1,2,6,2]
x, y = countmap(a), countmap(b)
[out]:

(Dict(7=>1,4=>3,2=>4,3=>2,5=>1,8=>1,1=>3),Dict(2=>3,3=>1,5=>1,6=>3,1=>4))
Dict{Int64,Int64} with 8 entries:
  7 => 1
  4 => 3
  2 => 7
  3 => 3
  5 => 2
  8 => 1
  6 => 3
  1 => 7
我可以将原始列表中的计数添加到
countmap
字典中,如下所示:

z = addcounts!(x, b)
[out]:

(Dict(7=>1,4=>3,2=>4,3=>2,5=>1,8=>1,1=>3),Dict(2=>3,3=>1,5=>1,6=>3,1=>4))
Dict{Int64,Int64} with 8 entries:
  7 => 1
  4 => 3
  2 => 7
  3 => 3
  5 => 2
  8 => 1
  6 => 3
  1 => 7
但是,如果我已经有了一本计算过的字典,我不能仅仅添加它们:

addcounts!(x, y)
[错误]:

MethodError: no method matching addcounts!(::Dict{Int64,Int64}, ::Dict{Int64,Int64})
Closest candidates are:
  addcounts!{T}(::Dict{T,V}, ::AbstractArray{T,N}) at /Users/liling.tan/.julia/v0.5/StatsBase/src/counts.jl:230
  addcounts!{T,W}(::Dict{T,V}, ::AbstractArray{T,N}, ::StatsBase.WeightVec{W,Vec<:AbstractArray{T<:Real,1}}) at /Users/liling.tan/.julia/v0.5/StatsBase/src/counts.jl:237
MethodError: no method matching +(::Dict{Int64,Int64}, ::Dict{Int64,Int64})
Closest candidates are:
  +(::Any, ::Any, ::Any, ::Any...) at operators.jl:138
[错误]:

MethodError: no method matching addcounts!(::Dict{Int64,Int64}, ::Dict{Int64,Int64})
Closest candidates are:
  addcounts!{T}(::Dict{T,V}, ::AbstractArray{T,N}) at /Users/liling.tan/.julia/v0.5/StatsBase/src/counts.jl:230
  addcounts!{T,W}(::Dict{T,V}, ::AbstractArray{T,N}, ::StatsBase.WeightVec{W,Vec<:AbstractArray{T<:Real,1}}) at /Users/liling.tan/.julia/v0.5/StatsBase/src/counts.jl:237
MethodError: no method matching +(::Dict{Int64,Int64}, ::Dict{Int64,Int64})
Closest candidates are:
  +(::Any, ::Any, ::Any, ::Any...) at operators.jl:138
是否有方法组合多个
countmap
s?

例如,在Python中:

>>> from collections import Counter
>>> a = [1,2,3,4,1,2,2,3,1,2,5,7,4,8,4]
>>> b = [1,2,5,3,1,6,1,6,1,2,6,2]
>>> x, y = Counter(a), Counter(b)
>>> z = x + y
>>> z
Counter({1: 7, 2: 7, 3: 3, 4: 3, 6: 3, 5: 2, 7: 1, 8: 1})

基本上问题是两本字典的总和。Julia标准库确实提供了这样的功能


你可以试试。
merge()
函数大致相当于在Python中添加计数器。如果您不想要一个完整的软件包,那么手工操作应该不难。

正如张军建议的那样DataStructures.jl提供了累加器类型(也称计数器)。具体来说,要获得问题的结果:

using DataStructures

x,y = counter(a),counter(b)

push!(x,y)          # push! replaces addcounts!

现在
x
包含
x
y

的总和,我想问题是,如果只有两个
proportionmap
s,就没有简单的方法“组合”它们。您至少需要知道两个数组的大小。当x累积时,y保持不变?确实如此<虽然code>x
不是一个Dict,但它可以这样访问。有关更多信息,请参阅的文档。