'How do I change all negative numbers to zero in python?
I have one list
list1 = [-10,1,2,3,9,-1]
I want to change the negative number to zero so that it looks like
list1 = [0,1,2,3,9,0]
how can I do it? Thanks!
Solution 1:[1]
You can use comprehensions:
list2 = [0 if i < 0 else i for i in list1]
or
list2 = [(i > 0) * i for i in list1]
Note that the second variant only works with Python 3 since True == 1
and False == 0
. It should work with Python 2 but there is no guarantee.
Solution 2:[2]
You can alternatively use the map
function
map(lambda x: max(x,0),list1)
Solution 3:[3]
Iterate through the list and if it's less that 0 change it
def do_the_thing(old_list):
new_list = []
for num in old_list:
if num < 0:
new_list.append(0)
else:
new_list.append(num)
return new_list
Solution 4:[4]
Another option is to is numpy like this:
list2 = numpy.array(list1)
list2 = list2 * (list2 >= 0)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | Thiru |
Solution 3 | sabbahillel |
Solution 4 | yoavsnake |