在 Julia 中获取集合中所有项目的数组 – collect() 方法
collect()
是 julia 中的一个内置函数,用于返回指定集合或迭代器中所有项目的数组。
Syntax:
collect(collection)
or
collect(element_type, collection)
Parameters:
- collection: Specified collection or iterator.
- element_type: Specified type of elements.
Returns: It returns an array of all items in the specified collection or iterator.
示例 1:
# Julia program to illustrate
# the use of collection() method
# Getting an array of all items in
# the specified collection or iterator.
println(collect(1:2:13))
println(collect(1:4))
println(collect(1:10))
println(collect(1:5:10))
输出:
[1, 3, 5, 7, 9, 11, 13]
[1, 2, 3, 4]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[1, 6]
示例 2:
# Julia program to illustrate
# the use of collection() method
# Getting an Array with the given
# element type of all items in
# a collection or iterable.
println(collect(Int32, 1:2:5))
println(collect(Int64, 1:5))
println(collect(Float32, 1:2:5))
println(collect(Float64, 1:5))
输出:
Int32[1, 3, 5]
[1, 2, 3, 4, 5]
Float32[1.0, 3.0, 5.0]
[1.0, 2.0, 3.0, 4.0, 5.0]