Julia:Dict的用法以及一些dict的常用函数

function printsum(a)
    println(summary(a), ": ", repr(a))
end

# dicts can be initialised directly:
a1 = Dict(1=>"one", 2=>"two")
printsum(a1)
#> Dict{Int64,String} with 2 entries: Dict(2=>"two",1=>"one")

# then added to
a1[3] = "three"
printsum(a1)
#> Dict{Int64,String} with 3 entries: Dict(2=>"two",3=>"three",1=>"one")
# dicts不会保持原来的顺序

# dicts may alose be created with the type explicitly set
a2 = Dict{Int64, AbstractString}()
a2[0] = "zero"
printsum(a2)
# Dict{Int64,AbstractString} with 1 entry:
# Dict{Int64,AbstractString}(Pair{Int64,AbstractString}(0, "zero"))

# dicts, like arrays, may also be created from comprehensions
a3 = Dict([i => @sprintf("%d", i) for i = 1:10])
printsum(a3)
#> Dict{Any,Any}: {5=>"5",4=>"4",6=>"6",7=>"7",2=>"2",10=>"10",9=>"9",8=>"8",3=>"3",1=>"1"}

# 这里简要介绍haskey的用法
myDict = Dict('a'=>2, 'b'=>3)
println(haskey(myDict, 'a')) # true
println(haskey(myDict, 'b')) # true
println(haskey(myDict, 'c')) # false

println('a' in keys(myDict)) # true
println(values(myDict)) # [3, 2]
printsum(collect(values(myDict)))
# 2-element Array{Int64,1}: [3, 2]
a = collect(values(myDict))
printsum(a)

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值