元组

Julia 中级

Anthony Markham

Quantitative Developer

元组 - 介绍

  • 一个有序且不可变的值集合。
  • 可包含任意数据类型的值。
  • 与向量相同的整数索引。
Julia 中级

元组 - 为什么?

优点

  • 需保护的数据用元组更安全。
  • 比向量更快、占用更少内存。

缺点

  • 不能对元组排序。
  • 不能追加、删除或更改值。
Julia 中级

元组 - 语法

  • 使用圆括号并用逗号分隔各值来定义元组。
my_tuple = (10, 20, 30, 40)
  • 元组可包含多种数据类型。
my_mixed_tuple = (10, "Hello", 30, true)
Julia 中级

元组 - 索引

  • 元组使用整数索引(与向量相同)。
my_tuple = (10, 20, 30, 40)
println(my_tuple[1])
10
println(my_tuple[2:3])
(20, 30)
Julia 中级

元组 - 不可变性

  • 元组创建后,不能添加或删除值。
  • 不能修改元组中的值。
my_tuple = (10, 20, 30, 40, 50)
append!(my_tuple, 60)
MethodError: no method matching append!(::NTuple{5, Int64}, ::Int64)
my_tuple = (10, 20, 30, 40, 50)
my_tuple[1] = 15
MethodError: no method matching setindex!(::NTuple{5, Int64}, ::Int64, ::Int64)
Julia 中级

元组 - 不可变性

  • 元组会记录自身元素个数,因为它不会改变。
  • 这会体现在变量的类型中。
my_vector = [10, 20, 30, 40, 50]
my_tuple = (10, 20, 30, 40, 50)

println(typeof(my_vector))
println(typeof(my_tuple))
Vector{Int64}
NTuple{5, Int64}
Julia 中级

元组 - NamedTuple

  • NamedTuple 是一种元组,其元素也可通过为值分配的名称来访问。
  • NamedTuple 中每个值都有唯一名称。
  • NamedTuple 与元组具有相同的不可变性。
my_named_tuple = (name="Anthony", country="Australia", city="Sydney")
println(my_named_tuple[1])
println(my_named_tuple.name)
Anthony
Anthony
Julia 中级

Ayo berlatih!

Julia 中级

Preparing Video For Download...