Reputation: 99
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
I'm traversing through a 3D array and if any value is not equal to 1, I would like to change it to 1.
Upvotes: 1
Views: 45
Reputation: 42778
If you use numpy
, just write:
arr[arr!=0] = 1
or if you only need a boolean array:
result = arr!=0
If you, on the other side, have a list of list of lists:
for plane in arr:
for row in plane:
row[:] = [int(item!=0) for item in row]
Upvotes: 4