Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterating through array

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?

like image 779
Swift Avatar asked Oct 31 '15 00:10

Swift


People also ask

How do you iterate through an array?

Iterating over an array You can iterate over an array using for loop or forEach loop. Using the for loop − Instead on printing element by element, you can iterate the index using for loop starting from 0 to length of the array (ArrayName. length) and access elements at each index.

How do you iterate through an array in HTML?

The forEach() method can now be used to iterate over the elements like an array and display them. The elements can be iterated through by using a normal for loop. The number of elements in the HTMLCollection can be found out by using the length property of the collection.

What is array iteration in JavaScript?

Array iteration methods perform some operation on each element of array. There are some different examples of Array iteration methods are given below. Array. forEach() function: The array. forEach() function calls the provided function(a callback function) once for each element of the array.


1 Answers

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]]
like image 194
John1024 Avatar answered Sep 20 '22 17:09

John1024