問題描述
如何在python中將所有負數更改為零? (How do I change all negative numbers to zero in python?)
我有一個列表
list1 = [‑10,1,2,3,9,‑1]
我想把負數改為零,這樣它看起來像
list1 = [0,1,2,3,9,0]
我該怎麼做?謝謝!
參考解法
方法 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.
方法 2:
You can alternatively use the map
function
map(lambda x: max(x,0),list1)
方法 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
方法 4:
Another option is to is numpy like this:
list2 = numpy.array(list1)
list2 = list2 * (list2 >= 0)
(by hassISC、Selcuk、Thiru、timlyo、yoavsnake)