You can use map and lambda in Python. Example:
newList= map(lambda y: max(0,min(255,y)), oldList)
You can even nest them if it is a multi-dimensional list. Example:
can=map(lambda x: map(lambda y: max(0.0,min(10.0,y)), x), can) can=[[max(min(u,10.0),0.0) for u in yy] for yy in can]
However, I think that using a for loop, as mentioned above, is faster than a lambda map for this case. I tried it on a rather large list (2 million float) and got -
time python trial.py real 0m14.060s user 0m10.542s sys 0m0.594s
Using for and -
time python trial.py real 0m15.813s user 0m12.243s sys 0m0.627s
Using the lambda map.
Another alternative is
newList=np.clip(oldList,0,255)
It is convenient for any dimension and very fast.
time python trial.py real 0m10.750s user 0m7.148s sys 0m0.735s
source share