dictionary - Julia : construct Dictionary with tuple values

标签 dictionary tuples julia

有没有可能在 Julia 中用元组值构造字典?

我试过了

dict = Dict{Int64, (Int64, Int64)}()
dict = Dict{Int64, Tuple(Int64, Int64)}()

我也尝试插入元组值,但之后我能够更改它们,因此它们不是元组。

有什么想法吗?

编辑:

parallel_check = Dict{Any, (Any, Any)}()

for i in 1:10
    dict[i] = (i+41, i+41)
end

dict[1][2] = 1 # not able to change this way, setindex error!

dict[1] = (3, 5) # this is acceptable. why?

最佳答案

元组类型(即元组的类型)的语法从 0.3 及更早版本中的 (Int64,Int64) 更改为 0.4 中的 Tuple{Int64,Int64} .注意花括号,而不是 Int64,Int64 周围的括号。您还可以通过将 typeof 函数应用于示例元组来在 REPL 中发现这一点:

julia> typeof((1,2))
Tuple{Int64,Int64}

所以你可以像这样构造你想要的字典:

julia> dict = Dict{Int64,Tuple{Int64,Int64}}()
Dict{Int64,Tuple{Int64,Int64}} with 0 entries

julia> dict[1] = (2,3)
(2,3)

julia> dict[2.0] = (3.0,4)
(3.0,4)

julia> dict
Dict{Int64,Tuple{Int64,Int64}} with 2 entries:
  2 => (3,4)
  1 => (2,3)

您问题的另一部分无关紧要,但无论如何我都会在这里回答:元组是不可变的——您不能更改元组中的某个元素。另一方面,字典是可变的,因此您可以将全新的元组值分配给字典中的插槽。换句话说,当您编写 dict[1] = (3,5) 时,您正在分配到 dict,这没关系,但是当您编写 dict[ 1][2] = 1 您分配到 dict 中位置 1 的元组中,这是不对的。

关于dictionary - Julia : construct Dictionary with tuple values,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36479331/

相关文章:

python - Python中的字符串到字典

dictionary - 不断向 map 添加数据

c++ - 查找元组元素的最大值 C++

tuples - 使用函数在 Julia 中重复值

julia - 如何在 Julia 中按元素应用函数?

emacs - 在 hunspell 个人词典中使用德语 Umlaute 正确保存的单词未被 emacs ispell 或 flyspell 识别为正确拼写

c++ - 检查所有 std::tuple 元素是否满足条件+设计问题

multithreading - julia: 可以玩多线程吗

c++ - 具有相同模板的不同参数