Using MapIndexed
:
Clear["Global`*"];
SeedRandom[1];
list = RandomInteger[{1, 10}, 20]
{2, 5, 1, 8, 1, 1, 9, 7, 1, 5, 2, 9, 6, 2, 2, 2, 4, 3, 2, 7}
condTable[k_List, n_, repl_ : 0] :=
MapIndexed[
If[First@#2 > First@FirstPosition[k, n, {Length@k}], repl, #] &, k
]
Usage:
condTable[list, 55, x] (* not in list case *)
{2, 5, 1, 8, 1, 1, 9, 7, 1, 5, 2, 9, 6, 2, 2, 2, 4, 3, 2, 7}
condTable[list, 4, x]
{2, 5, 1, 8, 1, 1, 9, 7, 1, 5, 2, 9, 6, 2, 2, 2, 4, x, x, x}
condTable[list, 9, g]
{2, 5, 1, 8, 1, 1, 9, g, g, g, g, g, g, g, g, g, g, g, g, g}
condTable[list, 7] (* default case *)
{2, 5, 1, 8, 1, 1, 9, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
Using SequenceReplace
:
Clear["Global`*"];
SeedRandom[1];
list = RandomInteger[{1, 10}, 20];
condTableSeqRep[k_List, n_, repl_ : 0] :=
SequenceReplace[k, {
{a___Except[n] ..} :> {a}
, {a___, n, b___} :>
Sequence @@ {a, n, Sequence @@ Table[repl, Length@{b}]}
}
]
condTableSeqRep[list, 55, x] (* not in list case *)
condTableSeqRep[list, 4, x]
condTableSeqRep[list, 9, g]
condTableSeqRep[list, 7] (* default case *)
(* same results *)