Maximum and minimum values ​​for list values ​​in Python

I have a list of values, and I would like to set the maximum value of any item in the list to 255, and the minimum value to 0, leaving those within the range unchanged.

oldList = [266, 40, -15, 13] newList = [255, 40, 0, 13] 

I'm currently doing

 for i in range(len(oldList)): if oldList[i] > 255: oldList[i] = 255 if oldList[i] < 0: oldList[i] = 0 

or similarly with newList.append(oldList[i]) .

But there must be a better way, right?

+6
source share
3 answers

Use the min , max functions:

 >>> min(266, 255) 255 >>> max(-15, 0) 0 

 >>> oldList = [266, 40, -15, 13] >>> [max(min(x, 255), 0) for x in oldList] [255, 40, 0, 13] 
+10
source

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 
+1
source

Another option is numpy.clip

 >>> import numpy as np >>> np.clip([266, 40, -15, 13], 0, 255) array([255, 40, 0, 13]) 
0
source

Source: https://habr.com/ru/post/957883/


All Articles