在 Julia 中替换集合的元素 – replace() 和 replace!() 方法
replace()
是 julia 中的一个内置函数,用于返回具有不同类型替换的指定数组的副本。这些所有操作都通过以下示例进行说明。
Syntax:
replace(A, old_new::Pair…; count::Integer)
or
replace(new::Function, A; count::Integer)
Parameters:
- A: Specified array.
- old_new::Pair: Specified values to get updated.
- count::Integer: This optional count value is used to replace at most count occurrences in total.
- new::Function: Specified set of instruction.
Returns: It returns a copy of the specified array with different types of replacement.
示例 1:此示例返回指定集合的副本。在此集合中,旧值被替换为新值,如果指定了 count,则最多替换 count 次。
# Julia program to illustrate
# the use of replace() method
# Getting a copy of the specified collection.
# In this collection old value get replaced
# with new value and if count is specified,
# then replace at most count occurrences in total.
println(replace([1, 3, 5, 4], 3 =>2, 5 =>3, count = 1))
println(replace([1, 3, 5, 4], 3 =>2, 5 =>3))
println(replace([1, false], false =>0))
println(replace([1, true], true =>1))
输出:
示例 2:此示例返回指定数组的副本,其中数组中的每个值 x 都替换为 new(x)。
# Julia program to illustrate
# the use of replace() method
# Getting a copy of a specified array
# where each value x in the array is
# replaced by new(x).
println(replace(x -> isodd(x) ? 2x : x, [1, 2, 3, 4]))
println(replace(x -> iseven(x) ? 2x : x, [1, 2, 3, 4]))
输出:
代替!()
replace!()
是 julia 中的一个内置函数,用于以不同类型的替换返回被替换的指定数组。这些所有操作都通过以下示例进行说明。
Syntax:
replace!(A, old_new::Pair…; count::Integer)
or
replace!(new::Function, A; count::Integer)
Parameters:
- A: Specified array.
- old_new::Pair: Specified values to get updated.
- count::Integer: This optional count value is used to replace at most count occurrences in total.
- new::Function: Specified set of instruction.
Returns: It returns the replaced array with different types of replacement method.
示例 1:此示例返回替换的集合。在此集合中,旧值被替换为新值,如果指定了 count,则最多替换 count 次。
# Julia program to illustrate
# the use of replace !() method
# Getting the replaced collection
# In this collection old value get replaced
# with new value and if count is specified,
# then replace at most count occurrences in total.
println(replace !([1, 3, 5, 4], 3 =>2, 5 =>3, count = 1))
println(replace !([1, 3, 5, 4], 3 =>2, 5 =>3))
println(replace !([1, false], false =>0))
println(replace !([1, true], true =>1))
输出:
示例 2:此示例返回替换后的指定数组,其中数组中的每个值 x 都被替换为 new(x)。
# Julia program to illustrate
# the use of replace !() method
# Getting the replaced specified array
# where each value x in the array is
# replaced by new(x).
println(replace !(x -> isodd(x) ? 2x : x, [1, 2, 3, 4]))
println(replace !(x -> iseven(x) ? 2x : x, [1, 2, 3, 4]))
输出: