Python中列表值的最大和最小上限

时间:2013-11-12 06:44:21

标签: python list

我有一个值列表,我想将列表中任何元素的最大值设置为255,将最小值设置为0,同时保持范围内的元素不变。

oldList = [266, 40, -15, 13]

newList = [255, 40, 0, 13]

目前我在做

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

或与newList.append(oldList[i])类似。

但必须有更好的方法,对吗?

3 个答案:

答案 0 :(得分:13)

使用minmax函数:

>>> 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]

答案 1 :(得分:2)

您可以在Python中使用map和lambda。 例如:

newList= map(lambda y: max(0,min(255,y)), oldList)

如果它是多维列表,您甚至可以嵌套它们。 例如:

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] 

但是我觉得在这种情况下使用上面提到的for循环比映射lambda更快。我在一个相当大的列表(200万浮动)上尝试了它并得到了 -

time python trial.py

real    0m14.060s
user    0m10.542s
sys     0m0.594s

使用for和 -

time python trial.py

real    0m15.813s
user    0m12.243s
sys     0m0.627s 

使用map lambda。

另一种选择是 -

newList=np.clip(oldList,0,255)

方便任何维度,速度非常快。

time python trial.py

real    0m10.750s
user    0m7.148s
sys     0m0.735s 

答案 2 :(得分:2)

另一个选项是numpy.clip

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