Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Maximum and minimum caps for list values in Python

Tags:

python

list

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?

like image 443
jayelm Avatar asked Nov 12 '13 06:11

jayelm


People also ask

How do you limit a value in a list in Python?

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 .

How do you set a cap in Python?

upper() method returns the uppercase string from the given string. It converts all lowercase characters to uppercase.

How to get the maximum and minimum values of lists in Python?

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

How to find the position of Min and Max elements in Python?

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.

How to solve the “Max and min” problem in Python?

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.

How to find the smallest and largest value in Python?

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 ()


2 Answers

Another option is is numpy.clip

>>> import numpy as np
>>> np.clip([266, 40, -15, 13], 0, 255)
array([255,  40,   0,  13])
like image 146
jayelm Avatar answered Oct 24 '22 06:10

jayelm


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]
like image 26
falsetru Avatar answered Oct 24 '22 06:10

falsetru