我有一个值列表,我想将列表中任何元素的最大值设置为255,将最小值设置为0,同时保持范围内的元素不变.
oldList = [266, 40, -15, 13]
newList = [255, 40, 0, 13]
Run Code Online (Sandbox Code Playgroud)
目前我在做
for i in range(len(oldList)):
if oldList[i] > 255:
oldList[i] = 255
if oldList[i] < 0:
oldList[i] = 0
Run Code Online (Sandbox Code Playgroud)
或类似的newList.append(oldList[i]).
但必须有比这更好的方法,对吗?
fal*_*tru 15
>>> min(266, 255)
255
>>> max(-15, 0)
0
Run Code Online (Sandbox Code Playgroud)
>>> oldList = [266, 40, -15, 13]
>>> [max(min(x, 255), 0) for x in oldList]
[255, 40, 0, 13]
Run Code Online (Sandbox Code Playgroud)
另一种选择是 numpy.clip
>>> import numpy as np
>>> np.clip([266, 40, -15, 13], 0, 255)
array([255, 40, 0, 13])
Run Code Online (Sandbox Code Playgroud)