Max Between a List and an Int
I Have a List Which I Need All Elements to Be Compared with an Int and Then Return a List. for Example: Mylist = [1, 5, -2, 7] Something Like This: Max(Mylist...
I have a list which I need all elements to be compared with an int and then return a list.
For example:
mylist = [1, 5, -2, 7]
something like this:
max(mylist, 0) => [1, 5, 0, 7]
How should I do that?
3 Answers
Something like this?
num = 0
mylist = [1, 5, -2, 7]
ans = [e if e>=num else num for e in mylist]
print(ans)
Output:
[1, 5, 0, 7]
Create a new list by
- iterating over the orignal
- make the comparison with the int
- keep the value that meets the criteria
NumPy library with the power of SIMD instructions provides that.
Generally, if you have a list or array called a:
import numpy as np
a = np.array([1, -2, 3, 4, 5, -6, -7, -8, 9])
note using a NumPy array instead of a
listmakes the computation much faster, faster than anyfor loop. Vice versa using NumPy forlists is not efficient as afor loop.
np.maximum(0, a)
Output:
[1 0 3 4 5 0 0 0 9]