【问题标题】:Turn Dict of Arrays to Array of Dicts with all unique combinations from the Dict of arrays将数组字典转换为字典数组,其中包含数组字典中的所有唯一组合
【发布时间】:2018-11-06 22:53:37
【问题描述】:

我有一个数组字典,我想将其转换为字典数组,其中每个字典都将具有来自数组字典的唯一组合。理想情况下,会有一个解决方案可以使用任意数量的 Dict 键,并以与 R 的 expand_grid 类似的方式工作(但适用于 Dicts 而不是 DataFrames)。在下面的示例中,我展示了一个我想将其转换为字典数组的示例字典。

d  = Dict{String,Array{Int}}(["a", "b", "c"] .=> [[1,2,3], [4], [5,6]])

desired_result = Array{Dict{String,Int}}([Dict{String,Int}(["a", "b", "c"] .=> [1,4,5]),
                                          Dict{String,Int}(["a", "b", "c"] .=> [1,4,6]),
                                          Dict{String,Int}(["a", "b", "c"] .=> [2,4,5]),
                                          Dict{String,Int}(["a", "b", "c"] .=> [2,4,6]),
                                          Dict{String,Int}(["a", "b", "c"] .=> [3,4,5]),
                                          Dict{String,Int}(["a", "b", "c"] .=> [3,4,6])])

当然,一种方法是附加到带有嵌套 for 循环的数组,但如果有更优雅的方法来做到这一点,那就太好了。

【问题讨论】:

    标签: arrays dictionary julia


    【解决方案1】:

    这是一个 2 行:

    d= Dict{String,Array{Int}}(["a", "b", "c"] .=> [[1,2,3], [4], [5,6]]);
    
    ks= sort(collect(keys(d)));
    [Dict(ks .=> val) for val in (collect(Iterators.product(getindex.((d,),ks)...))...,)]
    

    这会产生:

    6-element Array{Dict{String,Int64},1}:
     Dict("c"=>5,"b"=>4,"a"=>1)
     Dict("c"=>5,"b"=>4,"a"=>2)
     Dict("c"=>5,"b"=>4,"a"=>3)
     Dict("c"=>6,"b"=>4,"a"=>1)
     Dict("c"=>6,"b"=>4,"a"=>2)
     Dict("c"=>6,"b"=>4,"a"=>3)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-21
      • 1970-01-01
      • 2021-08-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多