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?

2

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

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 list makes the computation much faster, faster than any for loop. Vice versa using NumPy for lists is not efficient as a for loop.

np.maximum(0, a) 

Output:

[1 0 3 4 5 0 0 0 9] 

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy