广播代码之间的代数运算

问题描述 投票:1回答:1

我有两个dicts,我想从两个dicts中减去匹配值以生成第三个dict。

A = Dict("w" => 2, "x" => 3)
B = Dict("x" => 5, "w" => 7)
# Ideally I could go B .- A and get a dict like 
C = Dict("w" => 5, "x" => 2)
# but I get ERROR: ArgumentError: broadcasting over dictionaries and `NamedTuple`s is reserved

一个丑陋的解决方案是重载减法运算符,但我不想为像dict这样的内置类型重载,因为它害怕破坏其他代码。

import Base.-
function -(dictA::Dict, dictB::Dict)
   keys_of_A = keys(dictA)
   subtractions = get.(Ref(dictB), keys_of_A, 0) .- get.(Ref(dictA), keys_of_A, 0)
   return Dict(keys_of_A .=> subtractions)
end

Is there a cleaner way to do algebraic operations on matching values from different dicts?

dictionary julia
1个回答
5
投票

merge提供您想要的结果。

A = Dict("w" => 2, "x" => 3)
B = Dict("x" => 5, "w" => 7)
C = merge(-, B, A)

Dict{String,Int64} with 2 entries:
  "w" => 5
  "x" => 2

请注意,merge执行两个集合的并集,并通过执行给定的操作来组合公共密钥。所以,例如:

W = Dict("w" => 4)
merge(-, B, W)

Dict{String,Int64} with 2 entries:
  "w" => 3
  "x" => 5
© www.soinside.com 2019 - 2024. All rights reserved.