我如何编写一个函数,将数组中的所有负数替换为 0。
这是我目前所拥有的:
def negativesToZero(A):
for x in A:
if x < 0:
A.append(0)
else:
pass
print A
A = ([[1,-2],\
[-2,1]])
negativesToZero(A)
最佳答案
因为 A
是列表的列表:
>>> A = [[1, -2], [-2, 1]]
>>> for lst in A:
... for i, val in enumerate(lst):
... lst[i] = max(val, 0)
>>> print A
[[1, 0], [0, 1]]
或者使用列表理解:
>>> A = [[max(val, 0) for val in lst] for lst in A]
关于python - 替换数组中的负数,Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32107613/