I have a list of values and I'd like to set the maximum value of any element in the list to 255 and the minimum value to 0 while leaving those within the range unchanged.
oldList = [266, 40, -15, 13]
newList = [255, 40, 0, 13]
Currently I'm 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 has to be a better way than that, right?
To limit the values of the NumPy array ndarray to given range, use np. clip() or clip() method of ndarray . By specifying the minimum and maximum values in the argument, the out-of-range values are replaced with those values. This is useful when you want to limit the values to a range such as 0.0 ~ 1.0 or 0 ~ 255 .
upper() method returns the uppercase string from the given string. It converts all lowercase characters to uppercase.
The maximum and minimum values can be determined by the conventional max and min function of python and the extension of one to two lists can be dealt using the “ + ” operator. test_list1 = [1, 3, 4, 5, 2, 6] test_list2 = [3, 4, 8, 3, 10, 1] print ("The original list 1 is : " + str(test_list1))
Python Program to find the position of min and max elements of a list using min () and max () function. Allow user to enter the length of the list. Next, iterate the for loop and add the number in the list.
Let’s discuss certain ways in which this problem can be solved. The maximum and minimum values can be determined by the conventional max and min function of python and the extension of one to two lists can be dealt using the “ + ” operator.
Use Python’s min () and max () to find smallest and largest values in your data Call min () and max () with a single iterable or with any number of regular arguments Tweak the behavior of min () and max () with the key and default arguments Use comprehensions and generator expressions as arguments to min () and max ()
Another option is is numpy.clip
>>> import numpy as np
>>> np.clip([266, 40, -15, 13], 0, 255)
array([255, 40, 0, 13])
Use 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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With