julia 错误:字典中未定义地图

问题描述 投票:0回答:2
julia> hotcell2vocab = Dict([(cell, i-1+vocab_start)
                  for (i,cell)  in  enumerate(hotcell)]);

julia> vocab2hotcell = map(reverse, hotcell2vocab)
ERROR: map is not defined on dictionaries

hotcell2vocab
是一个
Dict
,有没有一种方法可以反转
Dict
中的键和值?

dictionary julia
2个回答
5
投票

这是您要找的吗?

julia> d = Dict(i => i+10 for i in 1:5)
Dict{Int64,Int64} with 5 entries:
  4 => 14
  2 => 12
  3 => 13
  5 => 15
  1 => 11

julia> d_rev = Dict(b=>a for (a,b) in d)
Dict{Int64,Int64} with 5 entries:
  14 => 4
  13 => 3
  11 => 1
  15 => 5
  12 => 2

当然,这假设您的字典中的值是唯一的。


0
投票
using BenchmarkTools
dic = Dict(zip(rand(10000),rand(10000)))
@benchmark Dict(map(reverse,collect(dic))) #403 us
@benchmark Dict(dic[i]=> i for i in keys(dic)) #2.84 ms
@benchmark Dict(reverse(i) for i in dic) #361 us
@benchmark Dict(value => key for (key, value) in dic) #351 us
@benchmark Dict(values(dic) .=> keys(dic)) #426 us
© www.soinside.com 2019 - 2024. All rights reserved.