Collections and Data Structures
Iteration
顺序迭代是通过 iterate
函数实现的。一般的 for
循环:
for i in iter # or "for i = iter"
# body
end
请提供您希望翻译的Markdown内容或文本。
next = iterate(iter)
while next !== nothing
(i, state) = next
# body
next = iterate(iter, state)
end
state
对象可以是任何东西,并应根据每种可迭代类型适当选择。有关定义自定义可迭代类型的更多详细信息,请参见 manual section on the iteration interface。
Base.iterate
— Functioniterate(iter [, state]) -> Union{Nothing, Tuple{Any, Any}}
推进迭代器以获取下一个元素。如果没有剩余元素,则应返回 nothing
。否则,应返回下一个元素和新的迭代状态的 2 元组。
Base.IteratorSize
— TypeIteratorSize(itertype::Type) -> IteratorSize
给定迭代器的类型,返回以下值之一:
SizeUnknown()
如果长度(元素数量)无法提前确定。HasLength()
如果有固定的有限长度。HasShape{N}()
如果有已知的长度加上多维形状的概念(如数组)。在这种情况下,N
应该给出维度的数量,并且axes
函数对迭代器是有效的。IsInfinite()
如果迭代器永远产生值。
默认值(对于未定义此函数的迭代器)是 HasLength()
。这意味着大多数迭代器被假定实现了 length
。
此特性通常用于在预分配结果空间的算法和逐步调整结果大小的算法之间进行选择。
julia> Base.IteratorSize(1:5)
Base.HasShape{1}()
julia> Base.IteratorSize((2,3))
Base.HasLength()
Base.IteratorEltype
— TypeIteratorEltype(itertype::Type) -> IteratorEltype
给定一个迭代器的类型,返回以下值之一:
EltypeUnknown()
如果迭代器所产生的元素类型事先未知。HasEltype()
如果元素类型已知,并且eltype
将返回一个有意义的值。
HasEltype()
是默认值,因为假设迭代器实现了 eltype
。
这个特性通常用于在预分配特定类型结果的算法和根据产生值的类型选择结果类型的算法之间进行选择。
julia> Base.IteratorEltype(1:5)
Base.HasEltype()
完全实现者:
AbstractRange
UnitRange
Tuple
Number
AbstractArray
BitSet
IdDict
Dict
WeakKeyDict
每行
AbstractString
Set
Pair
NamedTuple
Constructors and Types
Base.AbstractRange
— TypeBase.OrdinalRange
— TypeOrdinalRange{T, S} <: AbstractRange{T}
用于具有类型 T
的元素和类型 S
的间隔的序数范围的超类型。步长应始终是 oneunit
的精确倍数,并且 T
应该是“离散”类型,不能有小于 oneunit
的值。例如,Integer
或 Date
类型符合条件,而 Float64
则不符合(因为该类型可以表示小于 oneunit(Float64)
的值)。UnitRange
、StepRange
和其他类型是此类型的子类型。
Base.AbstractUnitRange
— TypeAbstractUnitRange{T} <: OrdinalRange{T, T}
具有步长为 oneunit(T)
的元素类型为 T
的范围的超类型。 UnitRange
和其他类型是其子类型。
Base.StepRange
— TypeStepRange{T, S} <: OrdinalRange{T, S}
具有类型 T
的元素和类型 S
的间隔的范围。每个元素之间的步长是恒定的,范围是根据类型为 T
的 start
和 stop
以及类型为 S
的 step
定义的。T
和 S
都不应为浮点类型。语法 a:b:c
在 b != 0
且 a
、b
和 c
都是整数的情况下会创建一个 StepRange
。
示例
julia> collect(StepRange(1, Int8(2), 10))
5-element Vector{Int64}:
1
3
5
7
9
julia> typeof(StepRange(1, Int8(2), 10))
StepRange{Int64, Int8}
julia> typeof(1:3:6)
StepRange{Int64, Int64}
Base.UnitRange
— TypeUnitRange{T<:Real}
一个由类型 T
的 start
和 stop
参数化的范围,填充了从 start
开始到超过 stop
的元素,元素之间间隔为 1
。语法 a:b
,其中 a
和 b
都是 Integer
,会创建一个 UnitRange
。
示例
julia> collect(UnitRange(2.3, 5.2))
3-element Vector{Float64}:
2.3
3.3
4.3
julia> typeof(1:10)
UnitRange{Int64}
Base.LinRange
— TypeLinRange{T,L}
一个范围,包含 len
个在其 start
和 stop
之间线性间隔的元素。间隔的大小由 len
控制,len
必须是一个 Integer
。
示例
julia> LinRange(1.5, 5.5, 9)
9-element LinRange{Float64, Int64}:
1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5, 5.0, 5.5
与使用 range
相比,直接构造 LinRange
应该有更少的开销,但不会尝试纠正浮点错误:
julia> collect(range(-0.1, 0.3, length=5))
5-element Vector{Float64}:
-0.1
0.0
0.1
0.2
0.3
julia> collect(LinRange(-0.1, 0.3, 5))
5-element Vector{Float64}:
-0.1
-1.3877787807814457e-17
0.09999999999999999
0.19999999999999998
0.3
另请参见 Logrange
以获取对数间隔的点。
General Collections
Base.isempty
— Functionisempty(collection) -> Bool
确定一个集合是否为空(没有元素)。
isempty(itr)
可能会消耗状态迭代器 itr
的下一个元素,除非定义了适当的 Base.isdone(itr)
方法。状态迭代器 应该 实现 isdone
,但在编写应该支持任何迭代器类型的通用代码时,您可能想要避免使用 isempty
。
示例
julia> isempty([])
true
julia> isempty([1 2 3])
false
isempty(condition)
如果没有任务在条件上等待,则返回 true
,否则返回 false
。
Base.isdone
— Functionisdone(itr, [state]) -> Union{Bool, Missing}
此函数为迭代器完成提供了快速路径提示。这对于希望避免消耗元素(如果它们不会暴露给用户)状态迭代器非常有用(例如,在检查 isempty
或 zip
中的完成状态时)。
希望选择此功能的状态迭代器应定义一个 isdone
方法,该方法根据迭代器是否完成返回 true/false。无状态迭代器不需要实现此函数。
如果结果为 missing
,调用者可以继续计算 iterate(x, state) === nothing
以得出明确的答案。
Base.empty!
— Functionempty!(collection) -> collection
从 collection
中移除所有元素。
示例
julia> A = Dict("a" => 1, "b" => 2)
Dict{String, Int64} with 2 entries:
"b" => 2
"a" => 1
julia> empty!(A);
julia> A
Dict{String, Int64}()
empty!(c::Channel)
通过在内部缓冲区上调用 empty!
来清空通道 c
。返回空通道。
Base.length
— Functionlength(collection) -> 整数
返回集合中元素的数量。
使用 lastindex
获取可索引集合的最后一个有效索引。
示例
julia> length(1:5)
5
julia> length([1, 2, 3, 4])
4
julia> length([1 2; 3 4])
4
Base.checked_length
— FunctionBase.checked_length(r)
计算 length(r)
,但在结果不适合 Union{Integer(eltype(r)),Int}
时,可能会检查溢出错误。
完全实现者:
AbstractRange
UnitRange
Tuple
Number
AbstractArray
BitSet
IdDict
Dict
WeakKeyDict
AbstractString
Set
NamedTuple
Iterable Collections
Base.in
— Functionin(item, collection) -> Bool
∈(item, collection) -> Bool
确定一个项目是否在给定的集合中,意思是它与通过迭代集合生成的一个值 ==
相等。返回一个 Bool
值,除非 item
是 missing
或 collection
包含 missing
但不包含 item
,在这种情况下返回 missing
(三值逻辑,与 any
和 ==
的行为相匹配)。
一些集合遵循稍微不同的定义。例如,Set
s 检查项目是否 isequal
于其中一个元素;Dict
s 查找 key=>value
对,并且 key
使用 isequal
进行比较。
要测试字典中是否存在键,请使用 haskey
或 k in keys(dict)
。对于上述提到的集合,结果始终是一个 Bool
。
当使用 in.(items, collection)
或 items .∈ collection
进行广播时,item
和 collection
都会被广播,这通常不是预期的结果。例如,如果两个参数都是向量(并且维度匹配),结果是一个向量,指示集合 items
中的每个值是否在 collection
中对应位置的值中。要获取一个指示 items
中每个值是否在 collection
中的向量,可以将 collection
包装在一个元组或 Ref
中,如下所示:in.(items, Ref(collection))
或 items .∈ Ref(collection)
。
另请参见:∉
,insorted
,contains
,occursin
,issubset
。
示例
julia> a = 1:3:20
1:3:19
julia> 4 in a
true
julia> 5 in a
false
julia> missing in [1, 2]
missing
julia> 1 in [2, missing]
missing
julia> 1 in [1, missing]
true
julia> missing in Set([1, 2])
false
julia> (1=>missing) in Dict(1=>10, 2=>20)
missing
julia> [1, 2] .∈ [2, 3]
2-element BitVector:
0
0
julia> [1, 2] .∈ ([2, 3],)
2-element BitVector:
0
1
Base.:∉
— Function∉(item, collection) -> Bool
∌(collection, item) -> Bool
∈
和 ∋
的否定,即检查 item
是否不在 collection
中。
当使用 items .∉ collection
进行广播时,item
和 collection
都会被广播,这通常不是预期的结果。例如,如果两个参数都是向量(并且维度匹配),结果是一个向量,指示 collection
中的每个值在 collection
中对应位置的值是否不在 items
中。要获取一个指示 items
中每个值是否不在 collection
中的向量,可以将 collection
包装在一个元组或 Ref
中,如下所示:items .∉ Ref(collection)
。
示例
julia> 1 ∉ 2:4
true
julia> 1 ∉ 1:3
false
julia> [1, 2] .∉ [2, 3]
2-element BitVector:
1
1
julia> [1, 2] .∉ ([2, 3],)
2-element BitVector:
1
0
Base.hasfastin
— FunctionBase.hasfastin(T)
确定计算 x ∈ collection
其中 collection::T
是否可以被视为“快速”操作(通常是常数或对数复杂度)。为了方便起见,提供了定义 hasfastin(x) = hasfastin(typeof(x))
,以便可以传递实例而不是类型。然而,应该为新类型定义接受类型参数的形式。
hasfastin(T)
的默认值对于 AbstractSet
、AbstractDict
和 AbstractRange
的子类型为 true
,否则为 false
。
Base.eltype
— Functioneltype(type)
确定通过迭代给定 type
的集合生成的元素的类型。对于字典类型,这将是 Pair{KeyType,ValType}
。为了方便起见,提供了定义 eltype(x) = eltype(typeof(x))
,这样可以传递实例而不是类型。然而,接受类型参数的形式应该为新类型定义。
示例
julia> eltype(fill(1f0, (2,2)))
Float32
julia> eltype(fill(0x1, (2,2)))
UInt8
Base.indexin
— Functionindexin(a, b)
返回一个数组,包含 b
中每个值在 a
中的第一个索引。输出数组在 a
不是 b
的成员的地方包含 nothing
。
示例
julia> a = ['a', 'b', 'c', 'b', 'd', 'a'];
julia> b = ['a', 'b', 'c'];
julia> indexin(a, b)
6-element Vector{Union{Nothing, Int64}}:
1
2
3
2
nothing
1
julia> indexin(b, a)
3-element Vector{Union{Nothing, Int64}}:
1
2
3
Base.unique
— Functionunique(itr)
返回一个数组,仅包含集合 itr
的唯一元素,这些元素是通过 isequal
和 hash
确定的,并按照每组等效元素最初出现的顺序排列。输入的元素类型得以保留。
另请参见:unique!
, allunique
, allequal
。
示例
julia> unique([1, 2, 6, 2])
3-element Vector{Int64}:
1
2
6
julia> unique(Real[1, 1.0, 2])
2-element Vector{Real}:
1
2
unique(f, itr)
返回一个数组,其中包含从 itr
中提取的每个唯一值所产生的 f
的一个值。
示例
julia> unique(x -> x^2, [1, -1, 3, -3, 4])
3-element Vector{Int64}:
1
3
4
此功能还可以用于提取数组中唯一元素的首次出现的 索引:
julia> a = [3.1, 4.2, 5.3, 3.1, 3.1, 3.1, 4.2, 1.7];
julia> i = unique(i -> a[i], eachindex(a))
4-element Vector{Int64}:
1
2
3
8
julia> a[i]
4-element Vector{Float64}:
3.1
4.2
5.3
1.7
julia> a[i] == unique(a)
true
unique(A::AbstractArray; dims::Int)
返回沿着维度 dims
的 A
的唯一区域。
示例
julia> A = map(isodd, reshape(Vector(1:8), (2,2,2)))
2×2×2 Array{Bool, 3}:
[:, :, 1] =
1 1
0 0
[:, :, 2] =
1 1
0 0
julia> unique(A)
2-element Vector{Bool}:
1
0
julia> unique(A, dims=2)
2×1×2 Array{Bool, 3}:
[:, :, 1] =
1
0
[:, :, 2] =
1
0
julia> unique(A, dims=3)
2×2×1 Array{Bool, 3}:
[:, :, 1] =
1 1
0 0
Base.unique!
— Functionunique!(f, A::AbstractVector)
从 A
中选择一个值,对于 f
应用于 A
元素所产生的每个唯一值,然后返回修改后的 A。
此方法自 Julia 1.1 起可用。
示例
julia> unique!(x -> x^2, [1, -1, 3, -3, 4])
3-element Vector{Int64}:
1
3
4
julia> unique!(n -> n%3, [5, 1, 8, 9, 3, 4, 10, 7, 2, 6])
3-element Vector{Int64}:
5
1
9
julia> unique!(iseven, [2, 3, 5, 7, 9])
2-element Vector{Int64}:
2
3
unique!(A::AbstractVector)
根据 isequal
和 hash
确定的标准移除重复项,然后返回修改后的 A
。unique!
将按照元素出现的顺序返回 A
的元素。如果您不关心返回数据的顺序,那么调用 (sort!(A); unique!(A))
将会更高效,只要 A
的元素可以被排序。
示例
julia> unique!([1, 1, 1])
1-element Vector{Int64}:
1
julia> A = [7, 3, 2, 3, 7, 5];
julia> unique!(A)
4-element Vector{Int64}:
7
3
2
5
julia> B = [7, 6, 42, 6, 7, 42];
julia> sort!(B); # unique! 能够更高效地处理已排序的数据。
julia> unique!(B)
3-element Vector{Int64}:
6
7
42
Base.allunique
— Functionallunique(itr) -> Bool
allunique(f, itr) -> Bool
如果 itr
中的所有值在与 isequal
比较时都是不同的,则返回 true
。或者如果 [f(x) for x in itr]
中的所有值都是不同的,则返回第二种方法。
请注意,allunique(f, itr)
可能会调用 f
少于 length(itr)
次。调用的确切次数被视为实现细节。
当输入已排序时,allunique
可能会使用专门的实现。
另请参见:unique
,issorted
,allequal
。
方法 allunique(f, itr)
至少需要 Julia 1.11。
示例
julia> allunique([1, 2, 3])
true
julia> allunique([1, 2, 1, 2])
false
julia> allunique(Real[1, 1.0, 2])
false
julia> allunique([NaN, 2.0, NaN, 4.0])
false
julia> allunique(abs, [1, -1, 2])
false
Base.allequal
— Functionallequal(itr) -> Bool
allequal(f, itr) -> Bool
如果 itr
中的所有值在与 isequal
比较时相等,则返回 true
。或者如果 [f(x) for x in itr]
中的所有值相等,则返回 true
,适用于第二种方法。
请注意,allequal(f, itr)
可能会调用 f
少于 length(itr)
次。调用的确切次数被视为实现细节。
allequal
函数需要至少 Julia 1.8。
方法 allequal(f, itr)
需要至少 Julia 1.11。
示例
julia> allequal([])
true
julia> allequal([1])
true
julia> allequal([1, 1])
true
julia> allequal([1, 2])
false
julia> allequal(Dict(:a => 1, :b => 1))
false
julia> allequal(abs2, [1, -1])
true
Base.reduce
— Methodreduce(op, itr; [init])
使用给定的二元运算符 op
对给定的集合 itr
进行归约。如果提供,初始值 init
必须是 op
的中性元素,对于空集合将返回该值。对于非空集合是否使用 init
是未指定的。
对于空集合,提供 init
是必要的,除了一些特殊情况(例如,当 op
是 +
、*
、max
、min
、&
、|
之一时),Julia 可以确定 op
的中性元素。
某些常用运算符的归约可能有特殊实现,应该使用这些实现:maximum
(itr)
、minimum
(itr)
、sum
(itr)
、prod
(itr)
、any
(itr)
、all
(itr)
。通过调用 reduce(
vcat
, arr)
或 reduce(
hcat
, arr)
可以高效地连接某些数组的数组。
归约的结合性依赖于实现。这意味着你不能使用非结合的操作,例如 -
,因为 reduce(-,[1,2,3])
应该被评估为 (1-2)-3
还是 1-(2-3)
是未定义的。请使用 foldl
或 foldr
来保证左结合或右结合。
某些操作会累积误差。如果归约可以分组执行,平行化将更容易。未来版本的 Julia 可能会改变算法。请注意,如果使用有序集合,元素不会被重新排序。
示例
julia> reduce(*, [2; 3; 4])
24
julia> reduce(*, [2; 3; 4]; init=-1)
-24
Base.reduce
— Methodreduce(f, A::AbstractArray; dims=:, [init])
沿着 A
的维度减少 2-参数函数 f
。dims
是一个指定要减少的维度的向量,关键字参数 init
是在减少中使用的初始值。对于 +
、*
、max
和 min
,init
参数是可选的。
减少的结合性依赖于实现;如果您需要特定的结合性,例如从左到右,您应该编写自己的循环或考虑使用 foldl
或 foldr
。有关 reduce
的文档,请参见。
示例
julia> a = reshape(Vector(1:16), (4,4))
4×4 Matrix{Int64}:
1 5 9 13
2 6 10 14
3 7 11 15
4 8 12 16
julia> reduce(max, a, dims=2)
4×1 Matrix{Int64}:
13
14
15
16
julia> reduce(max, a, dims=1)
1×4 Matrix{Int64}:
4 8 12 16
Base.foldl
— Methodfoldl(op, itr; [init])
类似于 reduce
,但保证左关联性。如果提供,关键字参数 init
将仅使用一次。通常,处理空集合时需要提供 init
。
另请参见 mapfoldl
,foldr
,accumulate
。
示例
julia> foldl(=>, 1:4)
((1 => 2) => 3) => 4
julia> foldl(=>, 1:4; init=0)
(((0 => 1) => 2) => 3) => 4
julia> accumulate(=>, (1,2,3,4))
(1, 1 => 2, (1 => 2) => 3, ((1 => 2) => 3) => 4)
Base.foldr
— Methodfoldr(op, itr; [init])
类似于 reduce
,但保证右结合性。如果提供,关键字参数 init
将仅使用一次。通常,在处理空集合时,需要提供 init
。
示例
julia> foldr(=>, 1:4)
1 => (2 => (3 => 4))
julia> foldr(=>, 1:4; init=0)
1 => (2 => (3 => (4 => 0)))
Base.maximum
— Functionmaximum(f, itr; [init])
返回对 itr
中每个元素调用函数 f
的最大结果。
对于空的 itr
,返回的值可以通过 init
指定。它必须是 max
的中性元素(即小于或等于任何其他元素),因为未指定 init
是否用于非空集合。
关键字参数 init
需要 Julia 1.6 或更高版本。
示例
julia> maximum(length, ["Julion", "Julia", "Jule"])
6
julia> maximum(length, []; init=-1)
-1
julia> maximum(sin, Real[]; init=-1.0) # 好,因为 sin 的输出 >= -1
-1.0
maximum(itr; [init])
返回集合中的最大元素。
对于空的 itr
,返回的值可以通过 init
指定。它必须是 max
的中性元素(即小于或等于任何其他元素),因为未指定 init
是否用于非空集合。
关键字参数 init
需要 Julia 1.6 或更高版本。
示例
julia> maximum(-20.5:10)
9.5
julia> maximum([1,2,3])
3
julia> maximum(())
ERROR: ArgumentError: reducing over an empty collection is not allowed; consider supplying `init` to the reducer
Stacktrace:
[...]
julia> maximum((); init=-Inf)
-Inf
maximum(A::AbstractArray; dims)
计算给定维度上数组的最大值。另请参见 max(a,b)
函数,该函数用于获取两个或多个参数的最大值,可以通过 max.(a,b)
元素级地应用于数组。
另请参见:maximum!
,extrema
,findmax
,argmax
。
示例
julia> A = [1 2; 3 4]
2×2 Matrix{Int64}:
1 2
3 4
julia> maximum(A, dims=1)
1×2 Matrix{Int64}:
3 4
julia> maximum(A, dims=2)
2×1 Matrix{Int64}:
2
4
maximum(f, A::AbstractArray; dims)
通过在给定维度上对数组的每个元素调用函数 f
来计算最大值。
示例
julia> A = [1 2; 3 4]
2×2 Matrix{Int64}:
1 2
3 4
julia> maximum(abs2, A, dims=1)
1×2 Matrix{Int64}:
9 16
julia> maximum(abs2, A, dims=2)
2×1 Matrix{Int64}:
4
16
Base.maximum!
— Functionmaximum!(r, A)
计算 A
在 r
的单例维度上的最大值,并将结果写入 r
。
当任何被修改的参数与其他参数共享内存时,行为可能会出乎意料。
示例
julia> A = [1 2; 3 4]
2×2 Matrix{Int64}:
1 2
3 4
julia> maximum!([1; 1], A)
2-element Vector{Int64}:
2
4
julia> maximum!([1 1], A)
1×2 Matrix{Int64}:
3 4
Base.minimum
— Functionminimum(f, itr; [init])
返回对 itr
中每个元素调用函数 f
的最小结果。
对于空的 itr
,返回的值可以通过 init
指定。它必须是 min
的中性元素(即大于或等于任何其他元素),因为未指定 init
是否用于非空集合。
关键字参数 init
需要 Julia 1.6 或更高版本。
示例
julia> minimum(length, ["Julion", "Julia", "Jule"])
4
julia> minimum(length, []; init=typemax(Int64))
9223372036854775807
julia> minimum(sin, Real[]; init=1.0) # 好,因为 sin 的输出 <= 1
1.0
minimum(itr; [init])
返回集合中的最小元素。
对于空的 itr
,返回的值可以通过 init
指定。它必须是 min
的中性元素(即大于或等于任何其他元素),因为未指定 init
是否用于非空集合。
关键字参数 init
需要 Julia 1.6 或更高版本。
示例
julia> minimum(-20.5:10)
-20.5
julia> minimum([1,2,3])
1
julia> minimum([])
ERROR: ArgumentError: reducing over an empty collection is not allowed; consider supplying `init` to the reducer
Stacktrace:
[...]
julia> minimum([]; init=Inf)
Inf
minimum(A::AbstractArray; dims)
计算给定维度上数组的最小值。另请参见 min(a,b)
函数,该函数用于获取两个或多个参数的最小值,可以通过 min.(a,b)
元素级地应用于数组。
另请参见: minimum!
, extrema
, findmin
, argmin
。
示例
julia> A = [1 2; 3 4]
2×2 Matrix{Int64}:
1 2
3 4
julia> minimum(A, dims=1)
1×2 Matrix{Int64}:
1 2
julia> minimum(A, dims=2)
2×1 Matrix{Int64}:
1
3
minimum(f, A::AbstractArray; dims)
通过在给定维度上对数组的每个元素调用函数 f
来计算最小值。
示例
julia> A = [1 2; 3 4]
2×2 Matrix{Int64}:
1 2
3 4
julia> minimum(abs2, A, dims=1)
1×2 Matrix{Int64}:
1 4
julia> minimum(abs2, A, dims=2)
2×1 Matrix{Int64}:
1
9
Base.minimum!
— Functionminimum!(r, A)
计算 A
在 r
的单例维度上的最小值,并将结果写入 r
。
当任何被修改的参数与其他参数共享内存时,行为可能会出乎意料。
示例
julia> A = [1 2; 3 4]
2×2 Matrix{Int64}:
1 2
3 4
julia> minimum!([1; 1], A)
2-element Vector{Int64}:
1
3
julia> minimum!([1 1], A)
1×2 Matrix{Int64}:
1 2
Base.extrema
— Functionextrema(itr; [init]) -> (mn, mx)
计算单次遍历中的最小值 mn
和最大值 mx
,并将它们作为一个 2 元组返回。
对于空的 itr
,返回的值可以通过 init
指定。它必须是一个 2 元组,其第一个和第二个元素分别是 min
和 max
的中性元素(即大于/小于或等于任何其他元素)。因此,当 itr
为空时,返回的 (mn, mx)
元组将满足 mn ≥ mx
。当指定 init
时,即使对于非空的 itr
也可以使用它。
关键字参数 init
需要 Julia 1.8 或更高版本。
示例
julia> extrema(2:10)
(2, 10)
julia> extrema([9,pi,4.5])
(3.141592653589793, 9.0)
julia> extrema([]; init = (Inf, -Inf))
(Inf, -Inf)
extrema(f, itr; [init]) -> (mn, mx)
计算应用于 itr
中每个元素的函数 f
的最小值 mn
和最大值 mx
,并将它们作为一个 2 元组返回。只对 itr
进行一次遍历。
对于空的 itr
,返回的值可以通过 init
指定。它必须是一个 2 元组,其第一个和第二个元素分别是 min
和 max
的中性元素(即大于/小于或等于任何其他元素)。它用于非空集合。注意:这意味着,对于空的 itr
,返回的值 (mn, mx)
满足 mn ≥ mx
,尽管对于非空的 itr
,它满足 mn ≤ mx
。这是一个“悖论”,但却是预期的结果。
此方法需要 Julia 1.2 或更高版本。
关键字参数 init
需要 Julia 1.8 或更高版本。
示例
julia> extrema(sin, 0:π)
(0.0, 0.9092974268256817)
julia> extrema(sin, Real[]; init = (1.0, -1.0)) # 好,因为 -1 ≤ sin(::Real) ≤ 1
(1.0, -1.0)
extrema(A::AbstractArray; dims) -> Array{Tuple}
计算给定维度上数组的最小值和最大值元素。
另请参见: minimum
, maximum
, extrema!
。
示例
julia> A = reshape(Vector(1:2:16), (2,2,2))
2×2×2 Array{Int64, 3}:
[:, :, 1] =
1 5
3 7
[:, :, 2] =
9 13
11 15
julia> extrema(A, dims = (1,2))
1×1×2 Array{Tuple{Int64, Int64}, 3}:
[:, :, 1] =
(1, 7)
[:, :, 2] =
(9, 15)
extrema(f, A::AbstractArray; dims) -> Array{Tuple}
计算在给定维度的 A
中应用于每个元素的 f
的最小值和最大值。
此方法需要 Julia 1.2 或更高版本。
Base.extrema!
— Functionextrema!(r, A)
计算 A
在 r
的单例维度上的最小值和最大值,并将结果写入 r
。
当任何被修改的参数与其他参数共享内存时,行为可能会出乎意料。
此方法需要 Julia 1.8 或更高版本。
示例
julia> A = [1 2; 3 4]
2×2 Matrix{Int64}:
1 2
3 4
julia> extrema!([(1, 1); (1, 1)], A)
2-element Vector{Tuple{Int64, Int64}}:
(1, 2)
(3, 4)
julia> extrema!([(1, 1);; (1, 1)], A)
1×2 Matrix{Tuple{Int64, Int64}}:
(1, 3) (2, 4)
Base.argmax
— Functionargmax(r::AbstractRange)
范围可以有多个最大元素。在这种情况下,argmax
将返回一个最大索引,但不一定是第一个。
argmax(f, domain)
从 domain
返回一个值 x
,使得 f(x)
达到最大值。如果 f(x)
有多个最大值,则将找到第一个。
domain
必须是一个非空的可迭代对象。
值的比较使用 isless
。
此方法需要 Julia 1.7 或更高版本。
示例
julia> argmax(abs, -10:5)
-10
julia> argmax(cos, 0:π/2:2π)
0.0
argmax(itr)
返回集合中最大元素的索引或键。如果有多个最大元素,则返回第一个。
集合不能为空。
索引与keys(itr)
和pairs(itr)
返回的类型相同。
值通过isless
进行比较。
示例
julia> argmax([8, 0.1, -9, pi])
1
julia> argmax([1, 7, 7, 6])
2
julia> argmax([1, 7, 7, NaN])
4
argmax(A; dims) -> indices
对于数组输入,返回给定维度上最大元素的索引。NaN
被视为大于所有其他值(除了 missing
)。
示例
julia> A = [1.0 2; 3 4]
2×2 Matrix{Float64}:
1.0 2.0
3.0 4.0
julia> argmax(A, dims=1)
1×2 Matrix{CartesianIndex{2}}:
CartesianIndex(2, 1) CartesianIndex(2, 2)
julia> argmax(A, dims=2)
2×1 Matrix{CartesianIndex{2}}:
CartesianIndex(1, 2)
CartesianIndex(2, 2)
Base.argmin
— Functionargmin(r::AbstractRange)
范围可以有多个最小元素。在这种情况下,argmin
将返回一个最小索引,但不一定是第一个。
argmin(f, domain)
返回一个来自 domain
的值 x
,使得 f(x)
最小。如果 f(x)
有多个最小值,则将找到第一个。
domain
必须是一个非空的可迭代对象。
NaN
被视为小于所有其他值,除了 missing
。
此方法需要 Julia 1.7 或更高版本。
示例
julia> argmin(sign, -10:5)
-10
julia> argmin(x -> -x^3 + x^2 - 10, -5:5)
5
julia> argmin(acos, 0:0.1:1)
1.0
argmin(itr)
返回集合中最小元素的索引或键。如果有多个最小元素,则返回第一个。
集合不能为空。
索引与keys(itr)
和pairs(itr)
返回的类型相同。
NaN
被视为小于所有其他值,除了missing
。
示例
julia> argmin([8, 0.1, -9, pi])
3
julia> argmin([7, 1, 1, 6])
2
julia> argmin([7, 1, 1, NaN])
4
argmin(A; dims) -> indices
对于数组输入,返回给定维度上最小元素的索引。NaN
被视为小于所有其他值,除了 missing
。
示例
julia> A = [1.0 2; 3 4]
2×2 Matrix{Float64}:
1.0 2.0
3.0 4.0
julia> argmin(A, dims=1)
1×2 Matrix{CartesianIndex{2}}:
CartesianIndex(1, 1) CartesianIndex(1, 2)
julia> argmin(A, dims=2)
2×1 Matrix{CartesianIndex{2}}:
CartesianIndex(1, 1)
CartesianIndex(2, 1)
Base.findmax
— Functionfindmax(f, domain) -> (f(x), index)
返回一个值对,该值对包含在值域中的一个值(f
的输出)和在 domain
中对应值的索引或键(f
的输入),使得 f(x)
达到最大值。如果存在多个最大点,则返回第一个。
domain
必须是一个非空的可迭代对象,支持 keys
。索引与 keys(domain)
返回的类型相同。
值的比较使用 isless
。
此方法需要 Julia 1.7 或更高版本。
示例
julia> findmax(identity, 5:9)
(9, 5)
julia> findmax(-, 1:10)
(-1, 1)
julia> findmax(first, [(1, :a), (3, :b), (3, :c)])
(3, 2)
julia> findmax(cos, 0:π/2:2π)
(1.0, 1)
findmax(itr) -> (x, index)
返回集合 itr
的最大元素及其索引或键。如果有多个最大元素,则返回第一个。值的比较使用 isless
。
索引与 keys(itr)
和 pairs(itr)
返回的类型相同。
另请参见: findmin
, argmax
, maximum
。
示例
julia> findmax([8, 0.1, -9, pi])
(8.0, 1)
julia> findmax([1, 7, 7, 6])
(7, 2)
julia> findmax([1, 7, 7, NaN])
(NaN, 4)
findmax(A; dims) -> (maxval, index)
对于数组输入,返回给定维度上的最大值及其索引。NaN
被视为大于所有其他值,除了 missing
。
示例
julia> A = [1.0 2; 3 4]
2×2 Matrix{Float64}:
1.0 2.0
3.0 4.0
julia> findmax(A, dims=1)
([3.0 4.0], CartesianIndex{2}[CartesianIndex(2, 1) CartesianIndex(2, 2)])
julia> findmax(A, dims=2)
([2.0; 4.0;;], CartesianIndex{2}[CartesianIndex(1, 2); CartesianIndex(2, 2);;])
findmax(f, A; dims) -> (f(x), index)
对于数组输入,返回在给定维度上最大化 f
的值及其对应值的索引。
示例
julia> A = [-1.0 1; -0.5 2]
2×2 Matrix{Float64}:
-1.0 1.0
-0.5 2.0
julia> findmax(abs2, A, dims=1)
([1.0 4.0], CartesianIndex{2}[CartesianIndex(1, 1) CartesianIndex(2, 2)])
julia> findmax(abs2, A, dims=2)
([1.0; 4.0;;], CartesianIndex{2}[CartesianIndex(1, 1); CartesianIndex(2, 2);;])
Base.findmin
— Functionfindmin(f, domain) -> (f(x), index)
返回一个值对,该值对包含在值域中的一个值(f
的输出)和在 domain
中对应值的索引或键(f
的输入),使得 f(x)
被最小化。如果存在多个最小点,则返回第一个。
domain
必须是一个非空的可迭代对象。
索引与 keys(domain)
和 pairs(domain)
返回的类型相同。
NaN
被视为小于所有其他值,除了 missing
。
此方法需要 Julia 1.7 或更高版本。
示例
julia> findmin(identity, 5:9)
(5, 1)
julia> findmin(-, 1:10)
(-10, 10)
julia> findmin(first, [(2, :a), (2, :b), (3, :c)])
(2, 1)
julia> findmin(cos, 0:π/2:2π)
(-1.0, 3)
findmin(itr) -> (x, index)
返回集合 itr
的最小元素及其索引或键。如果有多个最小元素,则返回第一个。NaN
被视为小于所有其他值,除了 missing
。
索引与 keys(itr)
和 pairs(itr)
返回的类型相同。
另请参见: findmax
, argmin
, minimum
.
示例
julia> findmin([8, 0.1, -9, pi])
(-9.0, 3)
julia> findmin([1, 7, 7, 6])
(1, 1)
julia> findmin([1, 7, 7, NaN])
(NaN, 4)
findmin(A; dims) -> (minval, index)
对于数组输入,返回给定维度上的最小值和索引。NaN
被视为小于所有其他值,除了 missing
。
示例
julia> A = [1.0 2; 3 4]
2×2 Matrix{Float64}:
1.0 2.0
3.0 4.0
julia> findmin(A, dims=1)
([1.0 2.0], CartesianIndex{2}[CartesianIndex(1, 1) CartesianIndex(1, 2)])
julia> findmin(A, dims=2)
([1.0; 3.0;;], CartesianIndex{2}[CartesianIndex(1, 1); CartesianIndex(2, 1);;])
findmin(f, A; dims) -> (f(x), index)
对于数组输入,返回在给定维度上最小化 f
的值及其对应值的索引。
示例
julia> A = [-1.0 1; -0.5 2]
2×2 Matrix{Float64}:
-1.0 1.0
-0.5 2.0
julia> findmin(abs2, A, dims=1)
([0.25 1.0], CartesianIndex{2}[CartesianIndex(2, 1) CartesianIndex(1, 2)])
julia> findmin(abs2, A, dims=2)
([1.0; 0.25;;], CartesianIndex{2}[CartesianIndex(1, 1); CartesianIndex(2, 1);;])
Base.findmax!
— Functionfindmax!(rval, rind, A) -> (maxval, index)
找到 A
的最大值及其对应的线性索引,并沿着 rval
和 rind
的单例维度存储结果。NaN
被视为大于所有其他值,除了 missing
。
当任何可变参数与其他参数共享内存时,行为可能会出乎意料。
Base.findmin!
— Functionfindmin!(rval, rind, A) -> (minval, index)
找到 A
的最小值及其对应的线性索引,沿着 rval
和 rind
的单例维度,并将结果存储在 rval
和 rind
中。NaN
被视为小于所有其他值,除了 missing
。
当任何可变参数与其他参数共享内存时,行为可能会出乎意料。
Base.sum
— Functionsum(f, itr; [init])
对 itr
中每个元素调用函数 f
的结果进行求和。
返回类型对于小于系统字大小的有符号整数为 Int
,对于小于系统字大小的无符号整数为 UInt
。对于所有其他参数,找到一个共同的返回类型,以便所有参数都被提升到该类型。
对于空的 itr
,返回的值可以通过 init
指定。它必须是加法单位元(即零),因为未指定 init
是否用于非空集合。
关键字参数 init
需要 Julia 1.6 或更高版本。
示例
julia> sum(abs2, [2; 3; 4])
29
注意 sum(A)
和 reduce(+, A)
在小整数元素类型的数组之间的重要区别:
julia> sum(Int8[100, 28])
128
julia> reduce(+, Int8[100, 28])
-128
在前一种情况下,整数被扩展到系统字大小,因此结果为 128。在后一种情况下,没有发生这样的扩展,整数溢出导致结果为 -128。
sum(itr; [init])
返回集合中所有元素的总和。
返回类型为 Int
,适用于小于系统字大小的有符号整数,返回类型为 UInt
,适用于小于系统字大小的无符号整数。对于所有其他参数,找到一个共同的返回类型,以便所有参数都被提升到该类型。
对于空的 itr
,返回的值可以通过 init
指定。它必须是加法单位(即零),因为未指定 init
是否用于非空集合。
关键字参数 init
需要 Julia 1.6 或更高版本。
另请参见: reduce
, mapreduce
, count
, union
.
示例
julia> sum(1:20)
210
julia> sum(1:20; init = 0.0)
210.0
sum(A::AbstractArray; dims)
对给定维度的数组元素求和。
示例
julia> A = [1 2; 3 4]
2×2 Matrix{Int64}:
1 2
3 4
julia> sum(A, dims=1)
1×2 Matrix{Int64}:
4 6
julia> sum(A, dims=2)
2×1 Matrix{Int64}:
3
7
sum(f, A::AbstractArray; dims)
对数组中每个元素调用函数 f
的结果在给定维度上求和。
示例
julia> A = [1 2; 3 4]
2×2 Matrix{Int64}:
1 2
3 4
julia> sum(abs2, A, dims=1)
1×2 Matrix{Int64}:
10 20
julia> sum(abs2, A, dims=2)
2×1 Matrix{Int64}:
5
25
Base.sum!
— Functionsum!(r, A)
对 A
的元素在 r
的单例维度上求和,并将结果写入 r
。
当任何被修改的参数与其他参数共享内存时,行为可能会出乎意料。
示例
julia> A = [1 2; 3 4]
2×2 Matrix{Int64}:
1 2
3 4
julia> sum!([1; 1], A)
2-element Vector{Int64}:
3
7
julia> sum!([1 1], A)
1×2 Matrix{Int64}:
4 6
Base.prod
— Functionprod(f, itr; [init])
返回将 f
应用于 itr
中每个元素的乘积。
返回类型对于小于系统字大小的有符号整数为 Int
,对于小于系统字大小的无符号整数为 UInt
。对于所有其他参数,找到一个共同的返回类型,以便所有参数都被提升到该类型。
对于空的 itr
,返回的值可以通过 init
指定。它必须是乘法单位(即一),因为未指定 init
是否用于非空集合。
关键字参数 init
需要 Julia 1.6 或更高版本。
示例
julia> prod(abs2, [2; 3; 4])
576
prod(itr; [init])
返回集合中所有元素的乘积。
返回类型对于小于系统字大小的有符号整数为 Int
,对于小于系统字大小的无符号整数为 UInt
。对于所有其他参数,找到一个共同的返回类型,以便所有参数都被提升到该类型。
对于空的 itr
,返回的值可以通过 init
指定。它必须是乘法单位(即一),因为未指定 init
是否用于非空集合。
关键字参数 init
需要 Julia 1.6 或更高版本。
示例
julia> prod(1:5)
120
julia> prod(1:5; init = 1.0)
120.0
prod(A::AbstractArray; dims)
在给定维度上乘以数组的元素。
示例
julia> A = [1 2; 3 4]
2×2 Matrix{Int64}:
1 2
3 4
julia> prod(A, dims=1)
1×2 Matrix{Int64}:
3 8
julia> prod(A, dims=2)
2×1 Matrix{Int64}:
2
12
prod(f, A::AbstractArray; dims)
在给定维度上,乘以对数组每个元素调用函数 f
的结果。
示例
julia> A = [1 2; 3 4]
2×2 Matrix{Int64}:
1 2
3 4
julia> prod(abs2, A, dims=1)
1×2 Matrix{Int64}:
9 64
julia> prod(abs2, A, dims=2)
2×1 Matrix{Int64}:
4
144
Base.prod!
— Functionprod!(r, A)
将 A
的元素在 r
的单例维度上相乘,并将结果写入 r
。
当任何被修改的参数与其他参数共享内存时,行为可能会出乎意料。
示例
julia> A = [1 2; 3 4]
2×2 Matrix{Int64}:
1 2
3 4
julia> prod!([1; 1], A)
2-element Vector{Int64}:
2
12
julia> prod!([1 1], A)
1×2 Matrix{Int64}:
3 8
Base.any
— Methodany(itr) -> Bool
测试布尔集合中是否有任何元素为 true
,一旦遇到 itr
中的第一个 true
值就返回 true
(短路)。要在 false
上短路,请使用 all
。
如果输入包含 missing
值,当所有非缺失值为 false
(或等价地,如果输入中没有 true
值)时,返回 missing
,遵循 三值逻辑。
另请参见:all
, count
, sum
, |
, , ||
。
示例
julia> a = [true,false,false,true]
4-element Vector{Bool}:
1
0
0
1
julia> any(a)
true
julia> any((println(i); v) for (i, v) in enumerate(a))
1
true
julia> any([missing, true])
true
julia> any([false, missing])
missing
Base.any
— Methodany(p, itr) -> Bool
确定谓词 p
是否对 itr
的任何元素返回 true
,一旦遇到 itr
中第一个 p
返回 true
的项就返回 true
(短路)。要在 false
上短路,请使用 all
。
如果输入包含 missing
值,当所有非缺失值为 false
(或等价地,如果输入不包含 true
值)时,返回 missing
,遵循 三值逻辑。
示例
julia> any(i->(4<=i<=6), [3,5,7])
true
julia> any(i -> (println(i); i > 3), 1:10)
1
2
3
4
true
julia> any(i -> i > 0, [1, missing])
true
julia> any(i -> i > 0, [-1, missing])
missing
julia> any(i -> i > 0, [-1, 0])
false
Base.any!
— Functionany!(r, A)
测试 A
中沿着 r
的单例维度是否有任何值为 true
,并将结果写入 r
。
当任何被修改的参数与其他参数共享内存时,行为可能会出乎意料。
示例
julia> A = [true false; true false]
2×2 Matrix{Bool}:
1 0
1 0
julia> any!([1; 1], A)
2-element Vector{Int64}:
1
1
julia> any!([1 1], A)
1×2 Matrix{Int64}:
1 0
Base.all
— Methodall(itr) -> Bool
测试布尔集合的所有元素是否为 true
,一旦在 itr
中遇到第一个 false
值就返回 false
(短路)。要在 true
上短路,请使用 any
。
如果输入包含 missing
值,当所有非缺失值为 true
(或等价地,如果输入中没有 false
值)时,返回 missing
,遵循 三值逻辑。
另请参见:all!
, any
, count
, &
, , &&
, allunique
。
示例
julia> a = [true,false,false,true]
4-element Vector{Bool}:
1
0
0
1
julia> all(a)
false
julia> all((println(i); v) for (i, v) in enumerate(a))
1
2
false
julia> all([missing, false])
false
julia> all([true, missing])
missing
Base.all
— Methodall(p, itr) -> Bool
确定谓词 p
是否对 itr
的所有元素返回 true
,一旦遇到 itr
中第一个 p
返回 false
的项就返回 false
(短路)。要在 true
上短路,请使用 any
。
如果输入包含 missing
值,如果所有非缺失值为 true
(或者等价地,如果输入不包含 false
值),则返回 missing
,遵循 三值逻辑。
示例
julia> all(i->(4<=i<=6), [4,5,6])
true
julia> all(i -> (println(i); i < 3), 1:10)
1
2
3
false
julia> all(i -> i > 0, [1, missing])
missing
julia> all(i -> i > 0, [-1, missing])
false
julia> all(i -> i > 0, [1, 2])
true
Base.all!
— Functionall!(r, A)
测试 A
中沿着 r
的单例维度的所有值是否为 true
,并将结果写入 r
。
当任何被修改的参数与其他参数共享内存时,行为可能会出乎意料。
示例
julia> A = [true false; true false]
2×2 Matrix{Bool}:
1 0
1 0
julia> all!([1; 1], A)
2-element Vector{Int64}:
0
0
julia> all!([1 1], A)
1×2 Matrix{Int64}:
1 0
Base.count
— Functioncount([f=identity,] itr; init=0) -> Integer
计算在 itr
中函数 f
返回 true
的元素数量。如果省略 f
,则计算 itr
中 true
元素的数量(这应该是一个布尔值集合)。init
可选地指定开始计数的值,因此也决定了输出类型。
init
关键字是在 Julia 1.6 中添加的。
示例
julia> count(i->(4<=i<=6), [2,3,4,5,6])
3
julia> count([true, false, true, true])
3
julia> count(>(3), 1:7, init=0x03)
0x07
count(
pattern::Union{AbstractChar,AbstractString,AbstractPattern},
string::AbstractString;
overlap::Bool = false,
)
返回 pattern
在 string
中匹配的数量。这相当于调用 length(findall(pattern, string))
,但更高效。
如果 overlap=true
,则匹配的序列可以在原始字符串中重叠索引,否则它们必须来自不相交的字符范围。
此方法至少需要 Julia 1.3。
将字符用作模式至少需要 Julia 1.7。
示例
julia> count('a', "JuliaLang")
2
julia> count(r"a(.)a", "cabacabac", overlap=true)
3
julia> count(r"a(.)a", "cabacabac")
2
count([f=identity,] A::AbstractArray; dims=:)
计算在给定维度上,f
返回 true
的 A
中元素的数量。
dims
关键字是在 Julia 1.5 中添加的。
init
关键字是在 Julia 1.6 中添加的。
示例
julia> A = [1 2; 3 4]
2×2 Matrix{Int64}:
1 2
3 4
julia> count(<=(2), A, dims=1)
1×2 Matrix{Int64}:
1 1
julia> count(<=(2), A, dims=2)
2×1 Matrix{Int64}:
2
0
Base.foreach
— Functionforeach(f, c...) -> Nothing
在可迭代对象 c
的每个元素上调用函数 f
。对于多个可迭代参数,f
按元素调用,当任何迭代器完成时,迭代停止。
当不需要 f
的结果时,应使用 foreach
而不是 map
,例如在 foreach(println, array)
中。
示例
julia> tri = 1:3:7; res = Int[];
julia> foreach(x -> push!(res, x^2), tri)
julia> res
3-element Vector{Int64}:
1
16
49
julia> foreach((x, y) -> println(x, " with ", y), tri, 'a':'z')
1 with a
4 with b
7 with c
Base.map
— Functionmap(f, c...) -> collection
通过对每个元素应用 f
来转换集合 c
。对于多个集合参数,逐元素应用 f
,并在任何一个集合耗尽时停止。
另见 map!
, foreach
, mapreduce
, mapslices
, zip
, Iterators.map
。
示例
julia> map(x -> x * 2, [1, 2, 3])
3-element Vector{Int64}:
2
4
6
julia> map(+, [1, 2, 3], [10, 20, 30, 400, 5000])
3-element Vector{Int64}:
11
22
33
map(f, A::AbstractArray...) -> N-array
当作用于具有相同 ndims
的多维数组时,它们必须具有相同的 axes
,结果也将如此。
另请参见 broadcast
,它允许不匹配的大小。
示例
julia> map(//, [1 2; 3 4], [4 3; 2 1])
2×2 Matrix{Rational{Int64}}:
1//4 2//3
3//2 4//1
julia> map(+, [1 2; 3 4], zeros(2,1))
ERROR: DimensionMismatch
julia> map(+, [1 2; 3 4], [1,10,100,1000], zeros(3,1)) # 迭代直到第三个耗尽
3-element Vector{Float64}:
2.0
13.0
102.0
Base.map!
— Functionmap!(function, destination, collection...)
类似于 map
,但将结果存储在 destination
中,而不是新的集合。destination
必须至少与最小的集合一样大。
当任何被修改的参数与其他参数共享内存时,行为可能会出乎意料。
另请参见: map
, foreach
, zip
, copyto!
。
示例
julia> a = zeros(3);
julia> map!(x -> x * 2, a, [1, 2, 3]);
julia> a
3-element Vector{Float64}:
2.0
4.0
6.0
julia> map!(+, zeros(Int, 5), 100:999, 1:3)
5-element Vector{Int64}:
101
103
105
0
0
map!(f, values(dict::AbstractDict))
通过将每个值从 val
转换为 f(val)
来修改 dict
。请注意,dict
的类型不能更改:如果 f(val)
不是 dict
的值类型的实例,则它将尽可能转换为值类型,否则将引发错误。
map!(f, values(dict::AbstractDict))
需要 Julia 1.2 或更高版本。
示例
julia> d = Dict(:a => 1, :b => 2)
Dict{Symbol, Int64} with 2 entries:
:a => 1
:b => 2
julia> map!(v -> v-1, values(d))
ValueIterator for a Dict{Symbol, Int64} with 2 entries. Values:
0
1
Base.mapreduce
— Methodmapreduce(f, op, itrs...; [init])
将函数 f
应用到 itrs
中的每个元素,然后使用二元函数 op
来减少结果。如果提供,init
必须是 op
的中性元素,将在空集合中返回。对于非空集合是否使用 init
是未指定的。一般来说,处理空集合时需要提供 init
。
mapreduce
在功能上等同于调用 reduce(op, map(f, itr); init=init)
,但通常执行速度更快,因为不需要创建中间集合。有关 reduce
和 map
的文档,请参见。
mapreduce
需要 Julia 1.2 或更高版本才能与多个迭代器一起使用。
示例
julia> mapreduce(x->x^2, +, [1:3;]) # == 1 + 4 + 9
14
归约的结合性依赖于实现。此外,一些实现可能会重用 f
的返回值,对于在 itr
中多次出现的元素。要保证左或右结合性并对每个值调用 f
,请使用 mapfoldl
或 mapfoldr
。
Base.mapfoldl
— Methodmapfoldl(f, op, itr; [init])
像 mapreduce
,但保证左关联性,如同 foldl
。如果提供,关键字参数 init
将被使用一次。在一般情况下,处理空集合时需要提供 init
。
Base.mapfoldr
— Methodmapfoldr(f, op, itr; [init])
类似于 mapreduce
,但保证右结合性,如同 foldr
。如果提供,关键字参数 init
将被使用一次。在一般情况下,处理空集合时需要提供 init
。
Base.first
— Functionfirst(coll)
获取可迭代集合的第一个元素。即使是空的,也会返回AbstractRange
的起始点。
另见:only
,firstindex
,last
。
示例
julia> first(2:2:10)
2
julia> first([1; 2; 3; 4])
1
first(itr, n::Integer)
获取可迭代集合 itr
的前 n
个元素,如果 itr
不够长,则返回更少的元素。
另见: startswith
, Iterators.take
.
此方法需要至少 Julia 1.6。
示例
julia> first(["foo", "bar", "qux"], 2)
2-element Vector{String}:
"foo"
"bar"
julia> first(1:6, 10)
1:6
julia> first(Bool[], 1)
Bool[]
first(s::AbstractString, n::Integer)
获取由s
的前n
个字符组成的字符串。
示例
julia> first("∀ϵ≠0: ϵ²>0", 0)
""
julia> first("∀ϵ≠0: ϵ²>0", 1)
"∀"
julia> first("∀ϵ≠0: ϵ²>0", 3)
"∀ϵ≠"
Base.last
— Functionlast(coll)
获取有序集合的最后一个元素,如果可以在 O(1) 时间内计算。这是通过调用 lastindex
来获取最后一个索引来实现的。即使 AbstractRange
为空,也返回其终点。
示例
julia> last(1:2:10)
9
julia> last([1; 2; 3; 4])
4
last(itr, n::Integer)
获取可迭代集合 itr
的最后 n
个元素,如果 itr
不够长,则返回更少的元素。
此方法需要至少 Julia 1.6。
示例
julia> last(["foo", "bar", "qux"], 2)
2-element Vector{String}:
"bar"
"qux"
julia> last(1:6, 10)
1:6
julia> last(Float64[], 1)
Float64[]
last(s::AbstractString, n::Integer)
获取由s
的最后n
个字符组成的字符串。
示例
julia> last("∀ϵ≠0: ϵ²>0", 0)
""
julia> last("∀ϵ≠0: ϵ²>0", 1)
"0"
julia> last("∀ϵ≠0: ϵ²>0", 3)
"²>0"
Base.front
— Functionfront(x::Tuple)::Tuple
返回一个 Tuple
,包含 x
的所有组件,除了最后一个。
示例
julia> Base.front((1,2,3))
(1, 2)
julia> Base.front(())
ERROR: ArgumentError: 不能在空元组上调用 front。
Base.tail
— Functiontail(x::Tuple)::Tuple
返回一个 Tuple
,包含 x
的所有组件,除了第一个。
另请参见: front
, rest
, first
, Iterators.peel
.
示例
julia> Base.tail((1,2,3))
(2, 3)
julia> Base.tail(())
ERROR: ArgumentError: 不能在空元组上调用 tail。
Base.step
— Functionstep(r)
获取AbstractRange
对象的步长。
示例
julia> step(1:10)
1
julia> step(1:2:10)
2
julia> step(2.5:0.3:10.9)
0.3
julia> step(range(2.5, stop=10.9, length=85))
0.1
Base.collect
— Methodcollect(collection)
返回一个包含集合或迭代器中所有项的 Array
。对于字典,返回一个 key=>value
Pair 的 Vector
。如果参数是类数组的或是具有 HasShape
特性的迭代器,则结果将具有与参数相同的形状和维数。
由 comprehensions 使用,以将 generator expression 转换为 Array
。因此,在生成器上,可以使用方括号表示法,而不是调用 collect
,见第二个示例。
示例
从 UnitRange{Int64}
集合中收集项:
julia> collect(1:3)
3-element Vector{Int64}:
1
2
3
从生成器中收集项(与 [x^2 for x in 1:3]
的输出相同):
julia> collect(x^2 for x in 1:3)
3-element Vector{Int64}:
1
4
9
Base.collect
— Methodcollect(element_type, collection)
返回一个具有给定元素类型的 Array
,包含集合或可迭代对象中的所有项。结果具有与 collection
相同的形状和维度数量。
示例
julia> collect(Float64, 1:2:5)
3-element Vector{Float64}:
1.0
3.0
5.0
Base.filter
— Functionfilter(f, a)
返回集合 a
的副本,移除 f
为 false
的元素。函数 f
接受一个参数。
将 a
作为元组的支持至少需要 Julia 1.4。
另请参见: filter!
, Iterators.filter
.
示例
julia> a = 1:10
1:10
julia> filter(isodd, a)
5-element Vector{Int64}:
1
3
5
7
9
filter(f)
创建一个函数,该函数使用 filter
通过函数 f
过滤其参数,即一个等价于 x -> filter(f, x)
的函数。
返回的函数类型为 Base.Fix1{typeof(filter)}
,可用于实现专门的方法。
示例
julia> (1, 2, Inf, 4, NaN, 6) |> filter(isfinite)
(1, 2, 4, 6)
julia> map(filter(iseven), [1:3, 2:4, 3:5])
3-element Vector{Vector{Int64}}:
[2]
[2, 4]
[4]
此方法至少需要 Julia 1.9。
filter(f, d::AbstractDict)
返回 d
的副本,移除 f
返回 false
的元素。函数 f
接收 key=>value
对。
示例
julia> d = Dict(1=>"a", 2=>"b")
Dict{Int64, String} with 2 entries:
2 => "b"
1 => "a"
julia> filter(p->isodd(p.first), d)
Dict{Int64, String} with 1 entry:
1 => "a"
filter(f, itr::SkipMissing{<:AbstractArray})
返回一个与给定 SkipMissing
迭代器包装的数组类似的向量,但所有缺失元素以及 f
返回 false
的元素都被移除。
此方法需要 Julia 1.2 或更高版本。
示例
julia> x = [1 2; missing 4]
2×2 Matrix{Union{Missing, Int64}}:
1 2
missing 4
julia> filter(isodd, skipmissing(x))
1-element Vector{Int64}:
1
Base.filter!
— Functionfilter!(f, a)
更新集合 a
,移除 f
返回 false
的元素。函数 f
接受一个参数。
示例
julia> filter!(isodd, Vector(1:10))
5-element Vector{Int64}:
1
3
5
7
9
filter!(f, d::AbstractDict)
更新 d
,移除 f
为 false
的元素。函数 f
接收 key=>value
对。
示例
julia> d = Dict(1=>"a", 2=>"b", 3=>"c")
Dict{Int64, String} with 3 entries:
2 => "b"
3 => "c"
1 => "a"
julia> filter!(p->isodd(p.first), d)
Dict{Int64, String} with 2 entries:
3 => "c"
1 => "a"
Base.replace
— Methodreplace(A, old_new::Pair...; [count::Integer])
返回集合 A
的副本,其中,对于每对 old=>new
在 old_new
中,所有 old
的出现都被替换为 new
。相等性使用 isequal
确定。如果指定了 count
,则最多替换 count
次出现。
结果的元素类型是基于 A
的元素类型和对中的 new
值的类型使用提升(参见 promote_type
)来选择。如果省略 count
并且 A
的元素类型是 Union
,则结果的元素类型将不包括被替换为不同类型值的单例类型:例如,如果 missing
被替换,Union{T,Missing}
将变为 T
。
另请参见 replace!
, splice!
, delete!
, insert!
.
需要版本 1.7 来替换 Tuple
的元素。
示例
julia> replace([1, 2, 1, 3], 1=>0, 2=>4, count=2)
4-element Vector{Int64}:
0
4
1
3
julia> replace([1, missing], missing=>0)
2-element Vector{Int64}:
1
0
Base.replace
— Methodreplace(new::Union{Function, Type}, A; [count::Integer])
返回 A
的副本,其中 A
中的每个值 x
都被 new(x)
替换。如果指定了 count
,则最多替换 count
个值(替换被定义为 new(x) !== x
)。
需要版本 1.7 才能替换 Tuple
的元素。
示例
julia> replace(x -> isodd(x) ? 2x : x, [1, 2, 3, 4])
4-element Vector{Int64}:
2
2
6
4
julia> replace(Dict(1=>2, 3=>4)) do kv
first(kv) < 3 ? first(kv)=>3 : kv
end
Dict{Int64, Int64} with 2 entries:
3 => 4
1 => 3
Base.replace!
— Functionreplace!(A, old_new::Pair...; [count::Integer])
对于每对 old=>new
在 old_new
中,将集合 A
中所有的 old
替换为 new
。相等性使用 isequal
确定。如果指定了 count
,则最多替换 count
次出现。另见 replace
。
示例
julia> replace!([1, 2, 1, 3], 1=>0, 2=>4, count=2)
4-element Vector{Int64}:
0
4
1
3
julia> replace!(Set([1, 2, 3]), 1=>0)
Set{Int64} with 3 elements:
0
2
3
replace!(new::Union{Function, Type}, A; [count::Integer])
用 new(x)
替换集合 A
中的每个元素 x
。如果指定了 count
,则最多替换 count
个值(替换被定义为 new(x) !== x
)。
示例
julia> replace!(x -> isodd(x) ? 2x : x, [1, 2, 3, 4])
4-element Vector{Int64}:
2
2
6
4
julia> replace!(Dict(1=>2, 3=>4)) do kv
first(kv) < 3 ? first(kv)=>3 : kv
end
Dict{Int64, Int64} with 2 entries:
3 => 4
1 => 3
julia> replace!(x->2x, Set([3, 6]))
Set{Int64} with 2 elements:
6
12
Base.rest
— FunctionBase.rest(collection[, itr_state])
通用函数,用于获取 collection
的尾部,从特定的迭代状态 itr_state
开始。如果 collection
本身是一个 Tuple
,则返回一个 Tuple
;如果 collection
是一个 AbstractArray
,则返回一个 AbstractVector
的子类型;如果 collection
是一个 AbstractString
,则返回一个 AbstractString
的子类型;否则返回一个任意迭代器,回退到 Iterators.rest(collection[, itr_state])
。
可以为用户定义的集合类型重载,以自定义在最终位置的 slurping in assignments 的行为,例如 a, b... = collection
。
Base.rest
至少需要 Julia 1.6。
另请参见: first
, Iterators.rest
, Base.split_rest
。
示例
julia> a = [1 2; 3 4]
2×2 Matrix{Int64}:
1 2
3 4
julia> first, state = iterate(a)
(1, 2)
julia> first, Base.rest(a, state)
(1, [3, 2, 4])
Base.split_rest
— FunctionBase.split_rest(collection, n::Int[, itr_state]) -> (rest_but_n, last_n)
用于拆分 collection
尾部的通用函数,从特定的迭代状态 itr_state
开始。返回一个包含两个新集合的元组。第一个集合包含尾部的所有元素,但不包括最后 n
个元素,这些元素构成第二个集合。
第一个集合的类型通常遵循 Base.rest
的类型,除了回退情况不是惰性求值,而是急切地收集到一个向量中。
可以为用户定义的集合类型重载,以自定义在非最终位置的 赋值中的吸取 行为,例如 a, b..., c = collection
。
Base.split_rest
至少需要 Julia 1.9。
另请参见: Base.rest
。
示例
julia> a = [1 2; 3 4]
2×2 Matrix{Int64}:
1 2
3 4
julia> first, state = iterate(a)
(1, 2)
julia> first, Base.split_rest(a, 1, state)
(1, ([3, 2], [4]))
Indexable Collections
Base.getindex
— Functiongetindex(collection, key...)
在集合中检索存储在给定键或索引处的值。语法 a[i,j,...]
被编译器转换为 getindex(a, i, j, ...)
。
示例
julia> A = Dict("a" => 1, "b" => 2)
Dict{String, Int64} with 2 entries:
"b" => 2
"a" => 1
julia> getindex(A, "a")
1
Base.setindex!
— Functionsetindex!(collection, value, key...)
在集合中以给定的键或索引存储给定的值。语法 a[i,j,...] = x
被编译器转换为 (setindex!(a, x, i, j, ...); x)
。
示例
julia> a = Dict("a"=>1)
Dict{String, Int64} with 1 entry:
"a" => 1
julia> setindex!(a, 2, "b")
Dict{String, Int64} with 2 entries:
"b" => 2
"a" => 1
Base.firstindex
— Functionfirstindex(collection) -> 整数
firstindex(collection, d) -> 整数
返回 collection
的第一个索引。如果给定 d
,则返回沿维度 d
的 collection
的第一个索引。
语法 A[begin]
和 A[1, begin]
分别降级为 A[firstindex(A)]
和 A[1, firstindex(A, 2)]
。
另请参见: first
, axes
, lastindex
, nextind
。
示例
julia> firstindex([1,2,4])
1
julia> firstindex(rand(3,4,5), 2)
1
Base.lastindex
— Functionlastindex(collection) -> 整数
lastindex(collection, d) -> 整数
返回 collection
的最后一个索引。如果给定 d
,则返回沿维度 d
的 collection
的最后一个索引。
语法 A[end]
和 A[end, end]
分别简化为 A[lastindex(A)]
和 A[lastindex(A, 1), lastindex(A, 2)]
。
另请参见: axes
, firstindex
, eachindex
, prevind
。
示例
julia> lastindex([1,2,4])
3
julia> lastindex(rand(3,4,5), 2)
4
完全实现者:
部分实现者:
Dictionaries
Dict
是标准字典。它的实现使用 hash
作为键的哈希函数,使用 isequal
来确定相等性。为自定义类型定义这两个函数,以覆盖它们在哈希表中的存储方式。
IdDict
是一个特殊的哈希表,其中键始终是对象标识。
WeakKeyDict
是一个哈希表实现,其中键是对对象的弱引用,因此即使在哈希表中被引用,也可能被垃圾回收。与 Dict
类似,它使用 hash
进行哈希和 isequal
进行相等性检查,不同于 Dict
,它在插入时不转换键。
Dict
可以通过将使用 =>
构造的对对象传递给 4d61726b646f776e2e436f64652822222c2022446963742229_40726566
构造函数来创建:Dict("A"=>1, "B"=>2)
。此调用将尝试从键和值推断类型信息(即此示例创建一个 Dict{String, Int64}
)。要显式指定类型,请使用语法 Dict{KeyType,ValueType}(...)
。例如,Dict{String,Int32}("A"=>1, "B"=>2)
。
字典也可以通过生成器创建。例如,Dict(i => f(i) for i = 1:10)
。
给定一个字典 D
,语法 D[x]
返回键 x
的值(如果存在)或抛出错误,而 D[x] = y
将键值对 x => y
存储在 D
中(替换键 x
的任何现有值)。对 D[...]
的多个参数会被转换为元组;例如,语法 D[x,y]
等价于 D[(x,y)]
,即它指的是由元组 (x,y)
键入的值。
Base.AbstractDict
— TypeAbstractDict{K, V}
键类型为 K
、值类型为 V
的字典类的超类型。 Dict
、IdDict
和其他类型是其子类型。 AbstractDict{K, V}
应该是 Pair{K, V}
的迭代器。
Base.Dict
— TypeDict([itr])
Dict{K,V}()
构造一个哈希表,键的类型为 K
,值的类型为 V
。键通过 isequal
进行比较,并通过 hash
进行哈希。
给定一个可迭代的单一参数,构造一个 Dict
,其键值对来自于参数生成的 2 元组 (key,value)
。
示例
julia> Dict([("A", 1), ("B", 2)])
Dict{String, Int64} with 2 entries:
"B" => 2
"A" => 1
或者,可以传递一系列成对的参数。
julia> Dict("A"=>1, "B"=>2)
Dict{String, Int64} with 2 entries:
"B" => 2
"A" => 1
键允许是可变的,但如果你确实修改了存储的键,哈希表可能会变得内部不一致,在这种情况下,Dict
将无法正常工作。如果需要修改键,IdDict
可以作为替代方案。
Base.IdDict
— TypeIdDict([itr])
IdDict{K,V}()
使用 objectid
作为哈希,===
作为相等性构造一个哈希表,键的类型为 K
,值的类型为 V
。有关更多帮助,请参见 Dict
和 IdSet
的集合版本。
在下面的示例中,Dict
的键都是 isequal
,因此它们被哈希为相同的值,从而被覆盖。IdDict
通过对象 ID 进行哈希,因此保留了 3 个不同的键。
示例
julia> Dict(true => "yes", 1 => "no", 1.0 => "maybe")
Dict{Real, String} with 1 entry:
1.0 => "maybe"
julia> IdDict(true => "yes", 1 => "no", 1.0 => "maybe")
IdDict{Any, String} with 3 entries:
true => "yes"
1.0 => "maybe"
1 => "no"
Base.WeakKeyDict
— TypeWeakKeyDict([itr])
WeakKeyDict()
构造一个哈希表,其中键是对可能被垃圾回收的对象的弱引用,即使在哈希表中被引用时也可能被回收。
有关更多帮助,请参见 Dict
。请注意,与 Dict
不同,WeakKeyDict
在插入时不会转换键,因为这将意味着键对象在插入之前没有被引用。
另请参见 WeakRef
。
Base.ImmutableDict
— TypeImmutableDict
ImmutableDict
是一个作为不可变链表实现的字典,适用于通过许多单独插入构建的小字典。请注意,无法删除一个值,尽管可以通过插入一个具有相同键的新值来部分覆盖和隐藏它。
ImmutableDict(KV::Pair)
为 key => value
对在 ImmutableDict
中创建一个新条目
- 使用
(key => value) in dict
来查看这个特定组合是否在属性集中 - 使用
get(dict, key, default)
来检索特定键的最新值
Base.PersistentDict
— TypePersistentDict
PersistentDict
是一个实现为哈希数组映射前缀树的字典,适用于需要持久性的情况,每个操作返回一个与之前不同的新字典,但其底层实现是空间高效的,并且可能在多个独立字典之间共享存储。
它的行为类似于 IdDict。
PersistentDict(KV::Pair)
示例
julia> dict = Base.PersistentDict(:a=>1)
Base.PersistentDict{Symbol, Int64} with 1 entry:
:a => 1
julia> dict2 = Base.delete(dict, :a)
Base.PersistentDict{Symbol, Int64}()
julia> dict3 = Base.PersistentDict(dict, :a=>2)
Base.PersistentDict{Symbol, Int64} with 1 entry:
:a => 2
Base.haskey
— Functionhaskey(collection, key) -> Bool
确定集合是否有给定 key
的映射。
示例
julia> D = Dict('a'=>2, 'b'=>3)
Dict{Char, Int64} with 2 entries:
'a' => 2
'b' => 3
julia> haskey(D, 'a')
true
julia> haskey(D, 'c')
false
Base.get
— Functionget(collection, key, default)
返回给定键存储的值,如果没有该键的映射,则返回给定的默认值。
对于元组和数字,此函数至少需要 Julia 1.7。
示例
julia> d = Dict("a"=>1, "b"=>2);
julia> get(d, "a", 3)
1
julia> get(d, "c", 3)
3
get(f::Union{Function, Type}, collection, key)
返回给定键存储的值,如果该键没有映射,则返回 f()
。 使用 get!
也可以将默认值存储在字典中。
这旨在使用 do
块语法调用
get(dict, key) do
# 默认值在这里计算
time()
end
Base.get!
— Functionget!(collection, key, default)
返回存储在给定键下的值,如果该键没有映射,则存储 key => default
,并返回 default
。
示例
julia> d = Dict("a"=>1, "b"=>2, "c"=>3);
julia> get!(d, "a", 5)
1
julia> get!(d, "d", 4)
4
julia> d
Dict{String, Int64} with 4 entries:
"c" => 3
"b" => 2
"a" => 1
"d" => 4
get!(f::Union{Function, Type}, collection, key)
返回给定键存储的值;如果该键没有映射,则存储 key => f()
,并返回 f()
。
这旨在使用 do
块语法调用。
示例
julia> squares = Dict{Int, Int}();
julia> function get_square!(d, i)
get!(d, i) do
i^2
end
end
get_square! (generic function with 1 method)
julia> get_square!(squares, 2)
4
julia> squares
Dict{Int64, Int64} with 1 entry:
2 => 4
Base.getkey
— Functiongetkey(collection, key, default)
如果在 collection
中存在与参数 key
匹配的键,则返回该键,否则返回 default
。
示例
julia> D = Dict('a'=>2, 'b'=>3)
Dict{Char, Int64} with 2 entries:
'a' => 2
'b' => 3
julia> getkey(D, 'a', 1)
'a': ASCII/Unicode U+0061 (category Ll: Letter, lowercase)
julia> getkey(D, 'd', 'a')
'a': ASCII/Unicode U+0061 (category Ll: Letter, lowercase)
Base.delete!
— Functiondelete!(collection, key)
删除集合中给定键的映射(如果存在),并返回集合。
示例
julia> d = Dict("a"=>1, "b"=>2)
Dict{String, Int64} with 2 entries:
"b" => 2
"a" => 1
julia> delete!(d, "b")
Dict{String, Int64} with 1 entry:
"a" => 1
julia> delete!(d, "b") # d 保持不变
Dict{String, Int64} with 1 entry:
"a" => 1
Base.pop!
— Methodpop!(collection, key[, default])
如果 key
存在于 collection
中,则删除并返回该映射,否则返回 default
,如果未指定 default
则抛出错误。
示例
julia> d = Dict("a"=>1, "b"=>2, "c"=>3);
julia> pop!(d, "a")
1
julia> pop!(d, "d")
ERROR: KeyError: key "d" not found
Stacktrace:
[...]
julia> pop!(d, "e", 4)
4
Base.keys
— Functionkeys(iterator)
对于具有键和值的迭代器或集合(例如数组和字典),返回一个键的迭代器。
Base.values
— Functionvalues(iterator)
对于具有键和值的迭代器或集合,返回一个值的迭代器。此函数默认简单地返回其参数,因为一般迭代器的元素通常被视为其“值”。
示例
julia> d = Dict("a"=>1, "b"=>2);
julia> values(d)
ValueIterator for a Dict{String, Int64} with 2 entries. Values:
2
1
julia> values([2])
1-element Vector{Int64}:
2
values(a::AbstractDict)
返回集合中所有值的迭代器。collect(values(a))
返回一个值的数组。当值内部存储在哈希表中时,例如 Dict
,返回的顺序可能会有所不同。但是 keys(a)
、values(a)
和 pairs(a)
都会迭代 a
并以相同的顺序返回元素。
示例
julia> D = Dict('a'=>2, 'b'=>3)
Dict{Char, Int64} with 2 entries:
'a' => 2
'b' => 3
julia> collect(values(D))
2-element Vector{Int64}:
2
3
Base.pairs
— Functionpairs(IndexLinear(), A)
pairs(IndexCartesian(), A)
pairs(IndexStyle(A), A)
一个迭代器,用于访问数组 A
的每个元素,返回 i => x
,其中 i
是元素的索引,x = A[i]
。与 pairs(A)
相同,不同之处在于可以选择索引的样式。也类似于 enumerate(A)
,但 i
将是 A
的有效索引,而 enumerate
始终从 1 开始计数,无论 A
的索引如何。
指定 IndexLinear()
确保 i
将是一个整数;指定 IndexCartesian()
确保 i
将是一个 Base.CartesianIndex
;指定 IndexStyle(A)
选择已定义为数组 A
的本地索引样式。
对底层数组的边界进行修改将使此迭代器失效。
示例
julia> A = ["a" "d"; "b" "e"; "c" "f"];
julia> for (index, value) in pairs(IndexStyle(A), A)
println("$index $value")
end
1 a
2 b
3 c
4 d
5 e
6 f
julia> S = view(A, 1:2, :);
julia> for (index, value) in pairs(IndexStyle(S), S)
println("$index $value")
end
CartesianIndex(1, 1) a
CartesianIndex(2, 1) b
CartesianIndex(1, 2) d
CartesianIndex(2, 2) e
另请参见 IndexStyle
,axes
。
pairs(collection)
返回一个迭代器,遍历任何将一组键映射到一组值的集合的 key => value
对。这包括数组,其中键是数组索引。当条目内部存储在哈希表中时,例如 Dict
的情况,返回的顺序可能会有所不同。但是 keys(a)
、values(a)
和 pairs(a)
都会遍历 a
并以相同的顺序返回元素。
示例
julia> a = Dict(zip(["a", "b", "c"], [1, 2, 3]))
Dict{String, Int64} with 3 entries:
"c" => 3
"b" => 2
"a" => 1
julia> pairs(a)
Dict{String, Int64} with 3 entries:
"c" => 3
"b" => 2
"a" => 1
julia> foreach(println, pairs(["a", "b", "c"]))
1 => "a"
2 => "b"
3 => "c"
julia> (;a=1, b=2, c=3) |> pairs |> collect
3-element Vector{Pair{Symbol, Int64}}:
:a => 1
:b => 2
:c => 3
julia> (;a=1, b=2, c=3) |> collect
3-element Vector{Int64}:
1
2
3
Base.merge
— Functionmerge(initial::Face, others::Face...)
合并 initial
面和 others
的属性,后面的面具有优先权。
merge(d::AbstractDict, others::AbstractDict...)
从给定的集合构造一个合并的集合。如果需要,结果集合的类型将被提升以适应合并集合的类型。如果另一个集合中存在相同的键,则该键的值将是最后列出的集合中的值。有关如何自定义处理具有相同键的值,请参见 mergewith
。
示例
julia> a = Dict("foo" => 0.0, "bar" => 42.0)
Dict{String, Float64} with 2 entries:
"bar" => 42.0
"foo" => 0.0
julia> b = Dict("baz" => 17, "bar" => 4711)
Dict{String, Int64} with 2 entries:
"bar" => 4711
"baz" => 17
julia> merge(a, b)
Dict{String, Float64} with 3 entries:
"bar" => 4711.0
"baz" => 17.0
"foo" => 0.0
julia> merge(b, a)
Dict{String, Float64} with 3 entries:
"bar" => 42.0
"baz" => 17.0
"foo" => 0.0
merge(a::NamedTuple, bs::NamedTuple...)
通过以左关联的方式合并两个或多个现有的命名元组来构造一个新的命名元组。合并是从左到右进行的,在命名元组对之间进行,因此左侧和右侧命名元组中存在的字段的顺序与它们在最左侧命名元组中找到的位置相同。然而,值是从包含该字段的最右侧命名元组中的匹配字段中获取的。仅在一对的最右侧命名元组中存在的字段会被附加到末尾。当只提供一个命名元组时,实施了一个后备,签名为 merge(a::NamedTuple)
。
合并三个或更多 NamedTuple
至少需要 Julia 1.1。
示例
julia> merge((a=1, b=2, c=3), (b=4, d=5))
(a = 1, b = 4, c = 3, d = 5)
julia> merge((a=1, b=2), (b=3, c=(d=1,)), (c=(d=2,),))
(a = 1, b = 3, c = (d = 2,))
merge(a::NamedTuple, iterable)
将键值对的可迭代对象解释为命名元组,并执行合并。
julia> merge((a=1, b=2, c=3), [:b=>4, :d=>5])
(a = 1, b = 4, c = 3, d = 5)
Base.mergewith
— Functionmergewith(combine, d::AbstractDict, others::AbstractDict...)
mergewith(combine)
merge(combine, d::AbstractDict, others::AbstractDict...)
从给定的集合构造一个合并的集合。如果需要,结果集合的类型将被提升以适应合并集合的类型。具有相同键的值将使用组合函数进行合并。柯里化形式 mergewith(combine)
返回函数 (args...) -> mergewith(combine, args...)
。
方法 merge(combine::Union{Function,Type}, args...)
作为 mergewith(combine, args...)
的别名仍然可用,以保持向后兼容性。
mergewith
需要 Julia 1.5 或更高版本。
示例
julia> a = Dict("foo" => 0.0, "bar" => 42.0)
Dict{String, Float64} with 2 entries:
"bar" => 42.0
"foo" => 0.0
julia> b = Dict("baz" => 17, "bar" => 4711)
Dict{String, Int64} with 2 entries:
"bar" => 4711
"baz" => 17
julia> mergewith(+, a, b)
Dict{String, Float64} with 3 entries:
"bar" => 4753.0
"baz" => 17.0
"foo" => 0.0
julia> ans == mergewith(+)(a, b)
true
Base.merge!
— Functionmerge!(d::AbstractDict, others::AbstractDict...)
使用其他集合中的键值对更新集合。另见 merge
。
示例
julia> d1 = Dict(1 => 2, 3 => 4);
julia> d2 = Dict(1 => 4, 4 => 5);
julia> merge!(d1, d2);
julia> d1
Dict{Int64, Int64} with 3 entries:
4 => 5
3 => 4
1 => 4
Base.mergewith!
— Functionmergewith!(combine, d::AbstractDict, others::AbstractDict...) -> d
mergewith!(combine)
merge!(combine, d::AbstractDict, others::AbstractDict...) -> d
使用其他集合中的对来更新集合。具有相同键的值将使用组合函数进行组合。柯里化形式 mergewith!(combine)
返回函数 (args...) -> mergewith!(combine, args...)
。
方法 merge!(combine::Union{Function,Type}, args...)
作为 mergewith!(combine, args...)
的别名仍然可用,以保持向后兼容性。
mergewith!
需要 Julia 1.5 或更高版本。
示例
julia> d1 = Dict(1 => 2, 3 => 4);
julia> d2 = Dict(1 => 4, 4 => 5);
julia> mergewith!(+, d1, d2);
julia> d1
Dict{Int64, Int64} with 3 entries:
4 => 5
3 => 4
1 => 6
julia> mergewith!(-, d1, d1);
julia> d1
Dict{Int64, Int64} with 3 entries:
4 => 0
3 => 0
1 => 0
julia> foldl(mergewith!(+), [d1, d2]; init=Dict{Int64, Int64}())
Dict{Int64, Int64} with 3 entries:
4 => 5
3 => 0
1 => 4
Base.sizehint!
— Functionsizehint!(s, n; first::Bool=false, shrink::Bool=true) -> s
建议集合 s
至少保留 n
个元素的容量。也就是说,如果你预计需要向 s
推送很多值,可以通过提前一次性分配容量来避免增量重新分配的成本;这可以提高性能。
如果 first
为 true
,则在集合开始之前保留任何额外的空间。这样,后续对 pushfirst!
(而不是 push!
)的调用可能会变得更快。提供此关键字可能会导致错误,如果集合没有序或不支持 pushfirst!
。
如果 shrink=true
(默认值),则如果当前容量大于 n
,集合的容量可能会减少。
另见 resize!
。
性能模型的说明
对于支持 sizehint!
的类型,
push!
和append!
方法通常可能(但不要求)预分配额外存储。对于在Base
中实现的类型,它们通常会这样做,使用针对一般用例优化的启发式方法。sizehint!
可能控制这种预分配。同样,它通常会对Base
中的类型执行此操作。- 对于支持这种预分配的类型,
empty!
几乎没有成本(且为 O(1))。
shrink
和 first
参数是在 Julia 1.11 中添加的。
Base.keytype
— Functionkeytype(T::Type{<:AbstractArray})
keytype(A::AbstractArray)
返回数组的键类型。这等于 keys(...)
结果的 eltype
,主要是为了与字典接口的兼容性。
示例
julia> keytype([1, 2, 3]) == Int
true
julia> keytype([1 2; 3 4])
CartesianIndex{2}
对于数组,此函数至少需要 Julia 1.2。
Base.valtype
— Functionvaltype(T::Type{<:AbstractArray})
valtype(A::AbstractArray)
返回数组的值类型。这与 eltype
相同,主要是为了与字典接口的兼容性。
示例
julia> valtype(["one", "two", "three"])
String
对于数组,此函数至少需要 Julia 1.2。
完全实现者:
部分实现者:
Set-Like Collections
Base.AbstractSet
— TypeBase.Set
— TypeSet{T} <: AbstractSet{T}
Set
是可变容器,提供快速的成员测试。
Set
对集合操作如 in
、union
和 intersect
有高效的实现。Set
中的元素是唯一的,这由元素的 isequal
定义决定。Set
中元素的顺序是实现细节,不能依赖。
另请参见: AbstractSet
, BitSet
, Dict
, push!
, empty!
, union!
, in
, isequal
示例
julia> s = Set("aaBca")
Set{Char} with 3 elements:
'a'
'c'
'B'
julia> push!(s, 'b')
Set{Char} with 4 elements:
'a'
'b'
'B'
'c'
julia> s = Set([NaN, 0.0, 1.0, 2.0]);
julia> -0.0 in s # isequal(0.0, -0.0) is false
false
julia> NaN in s # isequal(NaN, NaN) is true
true
Base.BitSet
— TypeBitSet([itr])
构造一个由给定可迭代对象生成的 Int
的排序集合,或者一个空集合。实现为位字符串,因此设计用于密集整数集合。如果集合将是稀疏的(例如,包含几个非常大的整数),请改用 Set
。
Base.IdSet
— TypeIdSet{T}([itr])
IdSet()
IdSet{T}() 使用 ===
作为与类型 T
的值的相等性构造一个集合(参见 Set
)。
在下面的示例中,所有值都是 isequal
,因此它们在普通的 Set
中被覆盖。IdSet
通过 ===
进行比较,因此保留了 3 个不同的值。
示例
julia> Set(Any[true, 1, 1.0])
Set{Any} with 1 element:
1.0
julia> IdSet{Any}(Any[true, 1, 1.0])
IdSet{Any} with 3 elements:
1.0
1
true
Base.union
— Functionunion(s, itrs...)
∪(s, itrs...)
构造一个包含所有参数中所有不同元素的对象。
第一个参数控制返回的容器类型。如果这是一个数组,它将保持元素首次出现的顺序。
Unicode ∪
可以通过在 Julia REPL 中输入 \cup
然后按下 tab 键来输入,在许多编辑器中也是如此。这是一个中缀运算符,允许 s ∪ itr
。
另请参见 unique
, intersect
, isdisjoint
, vcat
, Iterators.flatten
。
示例
julia> union([1, 2], [3])
3-element Vector{Int64}:
1
2
3
julia> union([4 2 3 4 4], 1:3, 3.0)
4-element Vector{Float64}:
4.0
2.0
3.0
1.0
julia> (0, 0.0) ∪ (-0.0, NaN)
3-element Vector{Real}:
0
-0.0
NaN
julia> union(Set([1, 2]), 2:3)
Set{Int64} with 3 elements:
2
3
1
Base.union!
— Functionunion!(s::Union{AbstractSet,AbstractVector}, itrs...)
构造传入集合的 union
并用结果覆盖 s
。对于数组保持顺序。
当任何被修改的参数与其他参数共享内存时,行为可能会出乎意料。
示例
julia> a = Set([3, 4, 5]);
julia> union!(a, 1:2:7);
julia> a
Set{Int64} with 5 elements:
5
4
7
3
1
Base.intersect
— Functionintersect(s, itrs...)
∩(s, itrs...)
构造一个包含所有参数中出现的元素的集合。
第一个参数控制返回的容器类型。如果这是一个数组,它将保持元素首次出现的顺序。
Unicode ∩
可以通过在 Julia REPL 中输入 \cap
然后按下 tab 键来输入,在许多编辑器中也是如此。这是一个中缀运算符,允许 s ∩ itr
。
另请参见 setdiff
, isdisjoint
, issubset
, issetequal
。
从 Julia 1.8 开始,intersect 返回的结果具有两个输入的类型提升后的 eltype 的 eltype
示例
julia> intersect([1, 2, 3], [3, 4, 5])
1-element Vector{Int64}:
3
julia> intersect([1, 4, 4, 5, 6], [6, 4, 6, 7, 8])
2-element Vector{Int64}:
4
6
julia> intersect(1:16, 7:99)
7:16
julia> (0, 0.0) ∩ (-0.0, 0)
1-element Vector{Real}:
0
julia> intersect(Set([1, 2]), BitSet([2, 3]), 1.0:10.0)
Set{Float64} with 1 element:
2.0
Base.setdiff
— Functionsetdiff(s, itrs...)
构造集合 s
中的元素,但不包括 itrs
中的任何可迭代对象。使用数组保持顺序。
另见 setdiff!
, union
和 intersect
。
示例
julia> setdiff([1,2,3], [3,4,5])
2-element Vector{Int64}:
1
2
Base.setdiff!
— Functionsetdiff!(s, itrs...)
从集合 s
中(就地)移除每个可迭代对象 itrs
中的每个元素。使用数组时保持顺序。
当任何被修改的参数与其他参数共享内存时,行为可能会出乎意料。
示例
julia> a = Set([1, 3, 4, 5]);
julia> setdiff!(a, 1:2:6);
julia> a
Set{Int64} with 1 element:
4
Base.symdiff
— Functionsymdiff(s, itrs...)
构造传入集合中元素的对称差。当 s
不是 AbstractSet
时,顺序保持不变。
另见 symdiff!
, setdiff
, union
和 intersect
。
示例
julia> symdiff([1,2,3], [3,4,5], [4,5,6])
3-element Vector{Int64}:
1
2
6
julia> symdiff([1,2,1], [2, 1, 2])
Int64[]
Base.symdiff!
— Functionsymdiff!(s::Union{AbstractSet,AbstractVector}, itrs...)
构造传入集合的对称差,并用结果覆盖 s
。当 s
是数组时,顺序会被保持。请注意,在这种情况下,元素的重复性是重要的。
当任何被修改的参数与其他参数共享内存时,行为可能会出乎意料。
Base.intersect!
— Functionintersect!(s::Union{AbstractSet,AbstractVector}, itrs...)
交集所有传入的集合,并用结果覆盖s
。对于数组保持顺序。
当任何被修改的参数与其他参数共享内存时,行为可能会出乎意料。
Base.issubset
— Functionissubset(a, b) -> Bool
⊆(a, b) -> Bool
⊇(b, a) -> Bool
确定 a
的每个元素是否也在 b
中,使用 in
。
示例
julia> issubset([1, 2], [1, 2, 3])
true
julia> [1, 2, 3] ⊆ [1, 2]
false
julia> [1, 2, 3] ⊇ [1, 2]
true
Base.in!
— Functionin!(x, s::AbstractSet) -> Bool
如果 x
在 s
中,返回 true
。如果不在,则将 x
推入 s
并返回 false
。这等价于 in(x, s) ? true : (push!(s, x); false)
,但可能有更高效的实现。
此函数至少需要 1.11。
示例
julia> s = Set{Any}([1, 2, 3]); in!(4, s)
false
julia> length(s)
4
julia> in!(0x04, s)
true
julia> s
Set{Any} with 4 elements:
4
2
3
1
Base.:⊈
— Function⊈(a, b) -> Bool
⊉(b, a) -> Bool
⊆
和 ⊇
的否定,即检查 a
不是 b
的子集。
示例
julia> (1, 2) ⊈ (2, 3)
true
julia> (1, 2) ⊈ (1, 2, 3)
false
Base.:⊊
— Function⊊(a, b) -> Bool
⊋(b, a) -> Bool
确定 a
是否是 b
的子集,但不等于 b
。
示例
julia> (1, 2) ⊊ (1, 2, 3)
true
julia> (1, 2) ⊊ (1, 2)
false
Base.issetequal
— Functionissetequal(a, b) -> Bool
确定 a
和 b
是否具有相同的元素。等价于 a ⊆ b && b ⊆ a
,但在可能的情况下更高效。
另请参见: isdisjoint
, union
。
示例
julia> issetequal([1, 2], [1, 2, 3])
false
julia> issetequal([1, 2], [2, 1])
true
issetequal(x)
创建一个函数,该函数使用 issetequal
将其参数与 x
进行比较,即一个等价于 y -> issetequal(y, x)
的函数。返回的函数类型为 Base.Fix2{typeof(issetequal)}
,可用于实现专门的方法。
此功能至少需要 Julia 1.11。
Base.isdisjoint
— Functionisdisjoint(a, b) -> Bool
确定集合 a
和 b
是否不相交。等价于 isempty(a ∩ b)
,但在可能的情况下更高效。
另请参见: intersect
, isempty
, issetequal
。
此函数至少需要 Julia 1.5。
示例
julia> isdisjoint([1, 2], [2, 3, 4])
false
julia> isdisjoint([3, 1], [2, 4])
true
isdisjoint(x)
创建一个函数,该函数使用 isdisjoint
将其参数与 x
进行比较,即一个等价于 y -> isdisjoint(y, x)
的函数。返回的函数类型为 Base.Fix2{typeof(isdisjoint)}
,可用于实现专门的方法。
此功能至少需要 Julia 1.11。
完全实现者:
部分实现者:
Dequeues
Base.push!
— Functionpush!(collection, items...) -> collection
将一个或多个 items
插入到 collection
中。如果 collection
是一个有序容器,项目将按给定顺序插入到末尾。
示例
julia> push!([1, 2, 3], 4, 5, 6)
6-element Vector{Int64}:
1
2
3
4
5
6
如果 collection
是有序的,使用 append!
将另一个集合的所有元素添加到其中。前面示例的结果等同于 append!([1, 2, 3], [4, 5, 6])
。对于 AbstractSet
对象,可以使用 union!
。
有关性能模型的说明,请参见 sizehint!
。
另请参见 pushfirst!
。
Base.pop!
— Functionpop!(collection) -> item
从 collection
中移除一个项目并返回它。如果 collection
是一个有序容器,则返回最后一个项目;对于无序容器,返回任意元素。
另请参见: popfirst!
, popat!
, delete!
, deleteat!
, splice!
, 和 push!
。
示例
julia> A=[1, 2, 3]
3-element Vector{Int64}:
1
2
3
julia> pop!(A)
3
julia> A
2-element Vector{Int64}:
1
2
julia> S = Set([1, 2])
Set{Int64} with 2 elements:
2
1
julia> pop!(S)
2
julia> S
Set{Int64} with 1 element:
1
julia> pop!(Dict(1=>2))
1 => 2
pop!(collection, key[, default])
如果 key
存在于 collection
中,则删除并返回该映射,否则返回 default
,如果未指定 default
则抛出错误。
示例
julia> d = Dict("a"=>1, "b"=>2, "c"=>3);
julia> pop!(d, "a")
1
julia> pop!(d, "d")
ERROR: KeyError: key "d" not found
Stacktrace:
[...]
julia> pop!(d, "e", 4)
4
Base.popat!
— Functionpopat!(a::Vector, i::Integer, [default])
移除给定 i
的项并返回它。后续项会被移动以填补结果间隙。当 i
不是 a
的有效索引时,返回 default
,如果未指定 default
则抛出错误。
另请参见: pop!
, popfirst!
, deleteat!
, splice!
.
此函数自 Julia 1.5 起可用。
示例
julia> a = [4, 3, 2, 1]; popat!(a, 2)
3
julia> a
3-element Vector{Int64}:
4
2
1
julia> popat!(a, 4, missing)
missing
julia> popat!(a, 4)
ERROR: BoundsError: attempt to access 3-element Vector{Int64} at index [4]
[...]
Base.pushfirst!
— Functionpushfirst!(collection, items...) -> collection
在 collection
的开头插入一个或多个 items
。
在许多其他编程语言中,这个函数被称为 unshift
。
示例
julia> pushfirst!([1, 2, 3, 4], 5, 6)
6-element Vector{Int64}:
5
6
1
2
3
4
Base.popfirst!
— Functionpopfirst!(collection) -> item
从 collection
中移除第一个 item
。
在许多其他编程语言中,这个函数被称为 shift
。
示例
julia> A = [1, 2, 3, 4, 5, 6]
6-element Vector{Int64}:
1
2
3
4
5
6
julia> popfirst!(A)
1
julia> A
5-element Vector{Int64}:
2
3
4
5
6
Base.insert!
— Functioninsert!(a::Vector, index::Integer, item)
在给定的 index
处将 item
插入到 a
中。index
是 item
在结果 a
中的索引。
另请参见:push!
, replace
, popat!
, splice!
。
示例
julia> insert!(Any[1:6;], 3, "here")
7-element Vector{Any}:
1
2
"here"
3
4
5
6
Base.deleteat!
— Functiondeleteat!(a::Vector, i::Integer)
删除给定 i
处的项并返回修改后的 a
。后续项会被移动以填补结果中的空缺。
另见: keepat!
, delete!
, popat!
, splice!
。
示例
julia> deleteat!([6, 5, 4, 3, 2, 1], 2)
5-element Vector{Int64}:
6
4
3
2
1
deleteat!(a::Vector, inds)
删除由 inds
给出的索引处的项,并返回修改后的 a
。后续项会被移动以填补产生的空缺。
inds
可以是一个迭代器或一个已排序且唯一的整数索引集合,或者是与 a
长度相同的布尔向量,其中 true
表示要删除的条目。
示例
julia> deleteat!([6, 5, 4, 3, 2, 1], 1:2:5)
3-element Vector{Int64}:
5
3
1
julia> deleteat!([6, 5, 4, 3, 2, 1], [true, false, true, false, true, false])
3-element Vector{Int64}:
5
3
1
julia> deleteat!([6, 5, 4, 3, 2, 1], (2, 2))
ERROR: ArgumentError: indices must be unique and sorted
Stacktrace:
[...]
Base.keepat!
— Functionkeepat!(a::Vector, inds)
keepat!(a::BitVector, inds)
移除所有未在 inds
中给出的索引处的项,并返回修改后的 a
。保留的项会被移动以填补结果中的空缺。
!!! 警告 当任何被修改的参数与其他参数共享内存时,行为可能会出乎意料。
inds
必须是一个排序且唯一的整数索引的迭代器。另见 deleteat!
。
!!! 兼容 "Julia 1.7" 此函数自 Julia 1.7 起可用。
示例
julia> keepat!([6, 5, 4, 3, 2, 1], 1:2:5)
3-element Vector{Int64}:
6
4
2
keepat!(a::Vector, m::AbstractVector{Bool})
keepat!(a::BitVector, m::AbstractVector{Bool})
逻辑索引的就地版本 a = a[m]
。也就是说,在长度相等的向量 a
和 m
上使用 keepat!(a, m)
将移除 a
中所有对应索引的 m
为 false
的元素。
示例
julia> a = [:a, :b, :c];
julia> keepat!(a, [true, false, true])
2-element Vector{Symbol}:
:a
:c
julia> a
2-element Vector{Symbol}:
:a
:c
Base.splice!
— Functionsplice!(a::Vector, index::Integer, [replacement]) -> item
移除给定索引处的项,并返回被移除的项。后续项向左移动以填补产生的空缺。如果指定了替换值,则将有序集合中的替换值插入到被移除的项的位置。
另见: replace
, delete!
, deleteat!
, pop!
, popat!
。
示例
julia> A = [6, 5, 4, 3, 2, 1]; splice!(A, 5)
2
julia> A
5-element Vector{Int64}:
6
5
4
3
1
julia> splice!(A, 5, -1)
1
julia> A
5-element Vector{Int64}:
6
5
4
3
-1
julia> splice!(A, 1, [-1, -2, -3])
6
julia> A
7-element Vector{Int64}:
-1
-2
-3
5
4
3
-1
要在不移除任何项的情况下在索引 n
之前插入 replacement
,请使用 splice!(collection, n:n-1, replacement)
。
splice!(a::Vector, indices, [replacement]) -> items
在指定的索引处移除项目,并返回一个包含被移除项目的集合。后续项目向左移动以填补结果中的空缺。如果指定了替换值,则将有序集合中的替换值插入到被移除项目的位置;在这种情况下,indices
必须是 AbstractUnitRange
。
要在不移除任何项目的情况下在索引 n
之前插入 replacement
,请使用 splice!(collection, n:n-1, replacement)
。
当任何被修改的参数与其他参数共享内存时,行为可能会出乎意料。
在 Julia 1.5 之前,indices
必须始终是 UnitRange
。
在 Julia 1.8 之前,如果在替换值中进行拼接,indices
必须是 UnitRange
。
示例
julia> A = [-1, -2, -3, 5, 4, 3, -1]; splice!(A, 4:3, 2)
Int64[]
julia> A
8-element Vector{Int64}:
-1
-2
-3
2
5
4
3
-1
Base.resize!
— Functionresize!(a::Vector, n::Integer) -> Vector
将 a
调整为包含 n
个元素。如果 n
小于当前集合长度,则保留前 n
个元素。如果 n
较大,则新元素不保证被初始化。
示例
julia> resize!([6, 5, 4, 3, 2, 1], 3)
3-element Vector{Int64}:
6
5
4
julia> a = resize!([6, 5, 4, 3, 2, 1], 8);
julia> length(a)
8
julia> a[1:6]
6-element Vector{Int64}:
6
5
4
3
2
1
Base.append!
— Functionappend!(collection, collections...) -> collection.
对于有序容器 collection
,将每个 collections
的元素添加到其末尾。
指定多个要附加的集合需要至少 Julia 1.6。
示例
julia> append!([1], [2, 3])
3-element Vector{Int64}:
1
2
3
julia> append!([1, 2, 3], [4, 5], [6])
6-element Vector{Int64}:
1
2
3
4
5
6
使用 push!
将单个项目添加到 collection
中,这些项目本身不在另一个集合中。前面示例的结果等同于 push!([1, 2, 3], 4, 5, 6)
。
有关性能模型的说明,请参见 sizehint!
。
另请参阅 vcat
用于向量,union!
用于集合,以及 prepend!
和 pushfirst!
用于相反的顺序。
Base.prepend!
— Functionprepend!(a::Vector, collections...) -> collection
将每个 collections
的元素插入到 a
的开头。
当 collections
指定多个集合时,顺序保持不变:collections[1]
的元素将最左侧出现在 a
中,依此类推。
指定多个集合以进行前置插入需要至少 Julia 1.6。
示例
julia> prepend!([3], [1, 2])
3-element Vector{Int64}:
1
2
3
julia> prepend!([6], [1, 2], [3, 4, 5])
6-element Vector{Int64}:
1
2
3
4
5
6
完全实现者:
Utility Collections
Core.Pair
— TypePair(x, y)
x => y
构造一个类型为 Pair{typeof(x), typeof(y)}
的 Pair
对象。元素存储在 first
和 second
字段中。它们也可以通过迭代访问(但 Pair
在广播操作中被视为一个单一的“标量”)。
另见 Dict
。
示例
julia> p = "foo" => 7
"foo" => 7
julia> typeof(p)
Pair{String, Int64}
julia> p.first
"foo"
julia> for x in p
println(x)
end
foo
7
julia> replace.(["xops", "oxps"], "x" => "o")
2-element Vector{String}:
"oops"
"oops"
Base.Pairs
— TypeBase.Pairs(values, keys) <: AbstractDict{eltype(keys), eltype(values)}
将一个可索引的容器转换为相同数据的字典视图。修改底层数据的键空间可能会使此对象失效。