How do I replace elements in a list matching a pattern?
Usual approach would be to use ReplaceAll
:
list = {0, 1, 1, 1, 2, 2, 2, 6};
list/.{x_?(# > 1 &) -> 1}
A slick approach would be
Boole /@ GreaterEqualThan[1] /@ list
Or even
Map[Min[#, 1] &, list]
Faster approach would be to use:
Unitize[list]
Clip[list]
All of them would give you:
{0, 1, 1, 1, 1, 1, 1, 1}
I just ran list = Table[RandomInteger[10], 100000]
and used Mr.Wizard's timeAvg function:
list /. {x_?(# > 1 &) -> 1} // timeAvg
Boole /@ GreaterEqualThan[1] /@ list // timeAvg
Map[Min[#, 1] &, l] // timeAvg
Unitize[l] // timeAvg
Clip[l] // timeAvg
0.0690836
0.0559747
0.00204779
0.000139352
0.00022492
I just googled "wolfram mathematica replace if". Based on the first link I was able to figure it out in a minute!
lst = {0, 1, 1, 1, 2, 2, 2, 6};
lst /. {x_?(# > 1 &) -> 1}
{0, 1, 1, 1, 1, 1, 1, 1}