2026a
# replace!
将集合中的指定元素替换为新的值,且可限制替换次数。
# 语法
replace!(A, old_new::Pair...; count::Integer)
replace!(new::Function, A; count::Integer)
# 说明
replace!(A, old_new::Pair...; count::Integer) 对集合 A 根据 old_new 键值对替换元素。 示例
replace!(new::Function, A; count::Integer) 对集合 A 中每个元素 x 替换为 new(x)。 示例
# 示例
替换元素
replace!([1, 2, 1, 3], 1=>0, 2=>4, count = 2)
4-element Vector{Int64}:
0
4
1
3
replace!(Set([1, 2, 3]), 1=>0)
Set{Int64} with 3 elements:
0
2
3
根据函数替换元素
replace!(x -> isodd(x) ? 2x : x, [1, 2, 3, 4])
4-element Vector{Int64}:
2
2
6
4
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
replace!(x->2x, Set([3, 6]))
Set{Int64} with 2 elements:
6
12
# 输入参数
A - 集合
任意集合,指定为向量、矩阵、字典等。
old_new - 替换键值对
old 为原集合的数据,new 为替换数据。
new - 函数
对集合 A 中每个元素 x 替换为 new(x)。
count - 替换最大数目
如果指定了 count,则总共最多替换 count 个元素。