python - 执行这些嵌套循环的最省时的方法是什么?

标签 python

for i in range(x):
    for j in range(y):
        for k in range(z):
            if arr[i][j][k] != 0:
                arr[i][j][k] = 1

我正在遍历一个 3D 数组,如果任何值不等于 1,我想将其更改为 1。

最佳答案

如果你使用numpy,只需写:

arr[arr!=0] = 1

或者如果您只需要一个 bool 数组:

result = arr!=0

如果你在另一边有一个列表的列表:

for plane in arr:
    for row in plane:
        row[:] = [int(item!=0) for item in row]

关于python - 执行这些嵌套循环的最省时的方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37386004/

相关文章:

Python MySQLdb 无法连接到服务器,SSL 问题

python - 如何在 Python 中使用 for 循环生成多个函数?

python - 如何在Python中填充矩阵以使其大小均匀

Python.Runtime.PythonException : since Python. NET 3.0 int 无法隐式转换为 Enum。使用枚举(int_value)

python - <type 'NoneType'> 做数学时出现问题

Python dict.get() 锁

python - 如何舍入 float ?

python - djangorest框架在create中动态设置外键

python - 如何在Python中从字典中打印2个或更多随机键

python - 针对 python 2 与 python 3 编译时,Cython 代码运行速度慢 125 倍