julia-dict字典(第13講)

1.字典分類:
    Dict                 是標準字典
    IdDict              鍵始終是對象標識
    WeakKeyDict 鍵是對對象的弱引用,因此即使在哈希表中進行引用也可能被垃圾回收
    ImmutableDict實現不可變鏈表的字典(無法刪除但可用新值覆蓋隱藏該值)
    AbstractDict字典抽象類型
2.1.字典構建Base.Dict

    Dict([itr])
    Dict{KeyType,ValueType}()#構造標準字典
    ImmutableDict(KV::Pair)     #在不可變字典中爲key => value對創建一個新條目
                                                #用於(key => value) in dict查看此特定組合是否在屬性集中

    #構建字典
    Dict([("A", 1), ("B", 2)])                            #可迭代參數創建

    Dict("A"=>1, "B"=>2)                               #傳遞參數對創建
    Dict{String,Int32}("A"=>1, "B"=>2)

    Dict(d[1] =>d[2] for d in zip("AB",[1,2]))#生成器創建
    Dict(i => f(i) for i = 1:3)
2.2.字典操作相關函數
    Base.haskey(collection, key) -> Bool# 確定字典中是否有給定映射key
    Base.sizehint!(s, n)                            #建議集合s至少保留n元素容量;可提高性能
        
    Base.keytype(T::Type{<:AbstractArray})#返回字數組類型,等於eltype的結果keys(...)
    Base.keytype(A::AbstractArray)              #返回數組類型
    Base.keytype(type)                                 #返回字典鍵類型
    valtype(T::Type{<:AbstractArray})           #返回數組的值類型
    valtype(A::AbstractArray)                          #返回數組的值類型
    valtype(type)                                             # 獲取字典值類型

    Base.get(collection, key, default)      # 獲取鍵對應的值,鍵不存返回默認值
    Base.get(f::Function, collection, key)# 獲取鍵對應的值,鍵不存返回函數;可用do來調用
    Base.get!(collection, key, default)      #獲取鍵對應值,否則默認值並存儲在字典中
    Base.get!(f::Function, collection, key)

    Base.getkey(collection, key, default)# 獲取字典中的鍵或默認值
    Base.keys(iterator)                           #獲取字典鍵iter
    Base.values(iterator)                         #獲取字典值iter

    Base.delete!(collection, key)# 刪除集合中給定鍵映射(無key則不刪除),返回集合
    Base.pop!(collection, key[, default])# 刪除集合中給定鍵映射;否則返回default(如無則拋異常)

    Base.merge(d::AbstractDict, others::AbstractDict...)#字典合併,類型自動提升;重複鍵爲未集合值;原字典不變
    Base.merge!(d::AbstractDict, others::AbstractDict...)#字典更新合併
    Base.merge(combine, d::AbstractDict, others::AbstractDict...)#字典合併,相同鍵的值用合併器合併
    Base.merge!(combine, d::AbstractDict, others::AbstractDict...)#字典更新合併-僅更新首字典

    Base.merge(d1::NamedTuple, bs::NamedTuple...)#命名元組合並;鍵名自左向右,值用最右邊的替代
    Base.merge(d1::NamedTuple, iterable)# 將鍵值對可迭代項解釋爲命名元組,然後執行合併
    
2.3.值對函數   
    Base.pairs(IndexLinear(), A)#構建值對iter(index,value)  x = A[i] i是有效索引
    Base.pairs(IndexCartesian(), A)
    Base.pairs(IndexStyle(A), A)#構建值對iter(index,value) -本機索引樣式任何一種  常用
    Base.pairs(collection)           #由集合構建值對iter
    Base.enumerate(collection)#由集合構建值對iter-不管索引,始終1開始計數

 

3.實例:
實例1:字典屬性類型
    julia> d = Dict('a'=>2, 'b'=>3)
    julia> haskey(d, 'a'),haskey(d, 'c')# (true, false)
    
    julia> sizehint!(d, 1)
    # Dict{Char,Int64} with 2 entries:
    # 'a' => 2
    # 'b' => 3

    julia> keytype(Dict('a'=> Int(1) , 'b'=>3))
    # Char

    julia> valtype(d)
    # Int64

    julia> keytype([1, 2, 3])
    # Int64

    julia> keytype([1, 2, 3]) == Int
    # true

    julia> keytype([1 2; 3 4])
    # CartesianIndex{2}

    julia> valtype(["one", "two", "three"])
    # String
實例2: 獲取字典中元素
    get(d, "a", -1)                       #-1

    key='g'                                 #必須和字典d鍵的類型相同Char
    get!(d, key) do
        100                                  #函數f(x)=100返回類型:必須和字典d值的類型相同
    end

    getkey(d, 'a', -1)# 'a': ASCII/Unicode U+0061 (category Ll: Letter, lowercase)
    pop!(d, "d")        #KeyError
    pop!(d, 'g')         #100
實例3:字典迭代
    julia> k=keys(d)
    """
    Base.KeySet for a Dict{Char,Int64} with 2 entries. Keys:
      'a'
      'b'
    """
    julia> v=values(d)
    """
    Base.ValueIterator for a Dict{Char,Int64} with 2 entries. Values:
      2
      3
     """ 
     julia> for v in k
           println(v)
           end
    """
    a
    b
    """
    julia> for v in v
           println(v)
           end
    """
    2
    3
    """
    julia> collect(keys(d))
    """
    2-element Array{Char,1}:
     'a'
     'b'
    """
    julia> collect(values(d))
    """
    2-element Array{Int64,1}:
     2
     3
     """
實例4.1:字典合併

    d1 = Dict("x1" => 0.01, "x2" => 3.14)
    d2 = Dict("x3" => 100, "x2" => 200)
    merge(d1, d2)
    """
    Dict{String,Float64} with 3 entries:
      "x1" => 0.01
      "x2" => 200.0
      "x3" => 100.0
    """

    merge(+, d1, d2)
    """
    Dict{String,Float64} with 3 entries:
      "x1" => 0.01
      "x2" => 203.14
      "x3" => 100.0
    """
================================================================================
實例4.2:字典更新合併

    merge!(d1, d2);
    d1
    """
    Dict{Int64,Int64} with 3 entries:
      "x1" => 0.01
      "x2" => 200.0
      "x3" => 100.0
    """

實例4.3:字典更新合併
    d1 = Dict("x1" => 0.01, "x2" => 3.14)
    merge!(+, d1, d2);

    julia> d1
    """
    Dict{Int64,Int64} with 3 entries:
      "x1" => 0.01
      "x2" => 203.14
      "x3" => 100.0
      """
實例4.5:命名元組合並
      
    merge((d1=1, d2=2, c=3), (d2=4, d3=5), (d3=5,d4=0,d2=10))# (d1 = 1, d2 = 10, c = 3, d3 = 5, d4 = 0)
    merge((d1=1, d2=2, c=3), [:d2=>4, :d=>5]) # (d1 = 1, d2 = 4, c = 3, d = 5)
實例5:值對

實例5.1:構建值對
    arr = ["x11" "x21"; "x12" "x22"; "x13" "x23"];
    """
    3×2 Array{String,2}:
     "x11"  "x21"
     "x12"  "x22"
     "x13"  "x23"
     """
    p0=enumerate(arr)
    Base.Iterators.Enumerate{Array{String,2}}(["x11" "x21"; "x12" "x22"; "x13" "x23"])

    p1= pairs(IndexStyle(arr), arr)
    """
    pairs(IndexLinear(), ::Array{String,2}) with 6 entries:
      1 => "x11"
      2 => "x12"
      3 => "x13"
      4 => "x21"
      5 => "x22"
      6 => "x23"
     """ 
    p2=pairs(arr)
    """
    pairs(::Array{String,2}) with 6 entries:
      CartesianIndex(1, 1) => "x11"
      CartesianIndex(2, 1) => "x12"
      CartesianIndex(3, 1) => "x13"
      CartesianIndex(1, 2) => "x21"
      CartesianIndex(2, 2) => "x22"
      CartesianIndex(3, 2) => "x23"
      """

 

實例5.2:迭代
    julia> for (index, value) in p0
                      println("$index $value")
                  end
    """
    1 x11
    2 x12
    3 x13
    4 x21
    5 x22
    6 x23
    """
    julia> for (index, value) in p1
               println("$index $value")
           end
     """
    1 x11
    2 x12
    3 x13
    4 x21
    5 x22
    6 x23
    """
    julia> s = view(arr, 1:2, :);
    s = view(arr, 1:2, :);

    julia> s
    """
    2×2 view(::Array{String,2}, 1:2, :) with eltype String:
     "x11"  "x21"
     "x12"  "x22
     """
    julia> for (index, value) in pairs(IndexStyle(s), s)
               println("$index $value")
           end
     """
    CartesianIndex(1, 1) x11
    CartesianIndex(2, 1) x12
    CartesianIndex(1, 2) x21
    CartesianIndex(2, 2) x22
    """
    julia> for(index,value) in p2
            println("$index $value")
                  end
    """
    CartesianIndex(1, 1) x11
    CartesianIndex(2, 1) x12
    CartesianIndex(3, 1) x13
    CartesianIndex(1, 2) x21
    CartesianIndex(2, 2) x22
    CartesianIndex(3, 2) x23
    """
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章