python - 替换数组中的负数,Python

标签 python arrays

我如何编写一个函数,将数组中的所有负数替换为 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/

相关文章:

java - 我怎样才能简化graphic2d的代码?

java - 改变已设置为相等的对象

MySQL - 在存在 GROUP BY 的情况下删除 JSON_ARRAYAGG 中的重复结果

javascript - 将 'prompt()' 的结果拆分为数组中的项目?

python - 使用 peewee python 支持动态列名称和排序方向的最佳方法

python - 如何对 Pandas DF 列中的值进行排序并删除重复项

python - Theano 随机梯度下降 NaN 输出

c - C语言编程中的插入排序

python - Tkinter PhotoImage 错误 "encountered an unsupported criticial chunk type "iDOT""

python - 检查索引处 numpy 数组的值