在 Julia 中访问指定键的值 – get()、get!() 和 getkey() 方法
get()
是 julia 中的内置函数,用于返回为指定键存储的值,如果不存在键映射,则返回给定的默认值。
Syntax:
get(collection, key, default)
Parameters:
- collection: Specified collection.
- key: Specified key present in the collection.
- default: Specified default value which is returned if no mapping for the key is present in the collection.
Returns: It returns the value stored for the specified key, or the given default value if no mapping for the key is present.
例子:
# Julia program to illustrate
# the use of get() method
# Getting the value stored for the
# specified key, or the given default
# value if no mapping for the key is present.
D = Dict("a"=>5, "b"=>10, "c"=>15);
println(get(D, "a", 1))
println(get(D, "b", 2))
println(get(D, "c", 3))
println(get(D, "d", 4))
输出:
5
10
15
4
得到!()
get!()
是 julia 中的一个内置函数,用于返回为指定键存储的值,或者如果不存在该键的映射,则存储键 => 默认值,并返回默认值。
Syntax:
get!(collection, key, default)
Parameters:
- collection: Specified collection.
- key: Specified key present in the collection.
- default: Specified default value.
Returns: It returns the value stored for the specified key, or if no mapping for the key is present, store key => default, and return default.
例子:
# Julia program to illustrate
# the use of get !() method
# Getting the value stored for
# the specified key, or if no
# mapping for the key is present,
# store key => default, and return default.
D = Dict("a"=>5, "b"=>10, "c"=>15);
println(get !(D, "a", 1))
println(get !(D, "b", 2))
println(get !(D, "c", 3))
println(get !(D, "d", 4))
println(D)
输出:
5
10
15
4
Dict("c"=>15, "b"=>10, "a"=>5, "d"=>4)
获取密钥()
getkey()
是 julia 中的一个内置函数,如果集合中存在键匹配参数键,则用于返回键匹配参数键,否则返回默认值。
Syntax:
get!(collection, key, default)
Parameters:
- collection: Specified collection.
- key: Specified key present in the collection.
- default: Specified default value.
Returns: It returns the key matching argument key if one exists in collection, otherwise return default.
例子:
# Julia program to illustrate
# the use of getkey() method
# Getting the key matching argument
# key if one exists in the collection,
# otherwise return default.
D = Dict("a"=>5, "b"=>10, "c"=>15);
println(getkey(D, "a", 1))
println(getkey(D, "b", 6))
println(getkey(D, "d", 1))
println(getkey(D, "e", 'z'))
输出:
a
b
1
z