I have an array of bools and now I want to swap those entries for numbers.
False => 0
True => 1
I have written two different pieces of code and I would like to know, which one is better and why. This is not so much about actually solving the problem, as about learning.
arr = [[True,False],[False,True],[True,True]]
for i,row in enumerate(arr):
for j,entry in enumerate(row):
if entry:
arr[i][j] = 1
else:
arr[i][j] = 0
print(arr)
And the second approach:
arr = [[True,False],[False,True],[True,True]]
for i in range(len(arr)):
for j in range(len(arr[i])):
if arr[i][j]:
arr[i][j] = 1
else:
arr[i][j] = 0
print(arr)
I read that there are ways to do this with importing itertools
or similar. I am really not a fan of importing things if it can be done with “on-board tools”, but should I rather be using them for this problem?
Let's define your array:
>>> arr = [[True,False],[False,True],[True,True]]
Now, let's convert the booleans to integer:
>>> [[int(i) for i in row] for row in arr]
[[1, 0], [0, 1], [1, 1]]
Alternatively, if we want to be more flexible about what gets substituted in, we can use a ternary statement:
>>> [[1 if i else 0 for i in row] for row in arr]
[[1, 0], [0, 1], [1, 1]]
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments