我有一个列表。
我希望将负数变成零,使其看起来像:
list1 = [-10,1,2,3,9,-1]
我希望将负数变成零,使其看起来像:
list1 = [0,1,2,3,9,0]
我该如何做呢?谢谢!
你可以使用推导式:
list2 = [0 if i < 0 else i for i in list1]
或者list2 = [(i > 0) * i for i in list1]
请注意,第二种变体仅适用于 Python 3,因为 True == 1
和 False == 0
。尽管可以在 Python 2 中使用,但不能保证正常工作。
map
函数。map(lambda x: max(x,0),list1)
另一个选择是使用类似于numpy的方式:
list2 = numpy.array(list1)
list2 = list2 * (list2 >= 0)
遍历列表,如果小于0,则更改它
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