📜  Julia 中的元组

📅  最后修改于: 2022-05-13 01:55:50.723000             🧑  作者: Mango

Julia 中的元组

Julia 中的元组是由逗号分隔的相同或不同数据类型的不同值的不可变集合。元组更像 Julia 中的数组,只是数组只接受相似数据类型的值。元组的值不能更改,因为元组是不可变的。元组是值的异构集合。
存储在元组中的值序列可以是任何类型,并且它们由整数索引。
元组的值在语法上由“逗号”分隔。虽然没有必要,但更常见的是通过关闭括号中的值序列来定义元组。这有助于更容易地理解 Julia 元组。
句法:

Tuple_name = (value1, value2, value3, ...)

例子:

Python
# Julia program to define Tuples
 
# Creating an empty tuple
tupl1 = ()
println(isempty(tupl1))
 
# Creating a tuple with similar values
tupl2 = (1, 2, 4, 5)
println(tupl2)
 
# Creating a tuple with mixed values
tupl3 = (1, 2, 3, "Hello Geeks")
println(tupl3)


Python
# Julia program to access elements
# from a Tuple
 
# Creating a tuple
tupl = ("Hello", "Geeks", 1, 2, 3, "Welcome")
 
# Accessing tuple elements
println(tupl[2])
 
# Accessing a range of elements
println(tupl[1:3])
 
# Using for loop to iterate over tuple
for i in tupl
    println(i)
end


Python
# Julia program to access elements
# from a Tuple
 
# Creating a tuple
tupl = ("Hello", "Geeks", 1, 2, 3, "Welcome")
 
# Reversing tuple
Rev_tupl = reverse(tupl)
println(Rev_tupl)
 
# Printing Tuple length
println(length(tupl))
 
# Using map operator
println(map(typeof, tupl))
 
# Checking if tuple is empty
println(isempty(tupl))


输出:

元组-Julia-Output-01

从元组访问元素

使用方括号 ([]) 可以轻松提取元组的元素。循环也可用于从元组中提取多个元素。此外,也可以通过在方括号内传递一个范围,就像字符串一样,从元组中提取一系列元素。
例子:

Python

# Julia program to access elements
# from a Tuple
 
# Creating a tuple
tupl = ("Hello", "Geeks", 1, 2, 3, "Welcome")
 
# Accessing tuple elements
println(tupl[2])
 
# Accessing a range of elements
println(tupl[1:3])
 
# Using for loop to iterate over tuple
for i in tupl
    println(i)
end

输出:

元组-Julia-Output-02

元组上的操作

元组允许根据用户需要对它们执行各种操作。这些操作可以是 reverse、length、map、isempty 等。

Python

# Julia program to access elements
# from a Tuple
 
# Creating a tuple
tupl = ("Hello", "Geeks", 1, 2, 3, "Welcome")
 
# Reversing tuple
Rev_tupl = reverse(tupl)
println(Rev_tupl)
 
# Printing Tuple length
println(length(tupl))
 
# Using map operator
println(map(typeof, tupl))
 
# Checking if tuple is empty
println(isempty(tupl))

输出:

元组-Julia-Output-03