在 Julia 中合并字典集合——merge() 和 merge!() 方法
merge()
是 julia 中的内置函数,用于从指定的集合构造合并集合。
Syntax:
merge(d::AbstractDict, others::AbstractDict…)
or
merge(combine, d::AbstractDict, others::AbstractDict…)
or
merge(a::NamedTuple, bs::NamedTuple…)
Parameters:
- d::AbstractDict: First specified collection.
- others::AbstractDict: Second specified collection.
- combine: Specified combing operation.
- NamedTuple: Specified different tuples..
Returns: It returns the merged collection.
示例 1:
# Julia program to illustrate
# the use of merge() method
# Getting the the merged collection.
a = Dict("a" => 1, "b" => 2)
b = Dict("c" => 3, "b" => 4)
prinln(merge(a, b))
输出:
示例 2:
# Julia program to illustrate
# the use of merge() method
# Getting the the merged collection
# along with specified operation
# over the key's value
a = Dict("a" => 1, "b" => 2)
b = Dict("c" => 3, "b" => 4)
prinln(merge(+, a, b))
输出:
示例 3:
# Julia program to illustrate
# the use of merge() method
# Getting the the merged tuple
println(merge((a = 5, b = 10), (b = 15, d = 20)))
println(merge((a = 5, b = 10), (b = 15, c =(d = 20, )), (c =(d = 25, ), )))
# Merging tuple of key-value pairs with
# iteration operation
println(merge((a = 5, b = 10, c = 15), [:b =>20, :d =>25]))
输出:
合并!()
merge!()
是 julia 中的一个内置函数,用于使用其他集合中的对更新集合。
Syntax:
merge!(d::AbstractDict, others::AbstractDict…)
or
merge!(combine, d::AbstractDict, others::AbstractDict…)
Parameters:
- d::AbstractDict: First specified collection.
- others::AbstractDict: Second specified collection.
- combine: Specified combing operation.
Returns: It returns the updated collection with pairs from the other collections.
示例 1:
# Julia program to illustrate
# the use of merge !() method
# Getting the updated collection with
# pairs from the other collections.
A = Dict("a" => 1, "b" => 2);
B = Dict("b" => 4, "c" => 5);
println(merge !(A, B))
输出:
Dict("c"=>5, "b"=>4, "a"=>1)
示例 2:
# Julia program to illustrate
# the use of merge !() method
# Getting the updated collection with
# pairs from the other collections
# with + operation
A = Dict("a" => 1, "b" => 2);
B = Dict("b" => 4, "c" => 5);
println(merge !(+, A, B))
输出:
Dict("c"=>5, "b"=>6, "a"=>1)