-1

If I have a 2D list (or list of lists):

[[1,0,1],
 [1,1,1],
 [0,0,0]]

How can I iterate this list and and convert all values to boolean for example:

    [[True,False,True],
     [True,True,True],
     [False,False,False]]

Using comprehensions instead of for loops would be ideal.

Retaining the old data isn't necessary but it may be simpler to just create a new set.

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
cc6g11
  • 477
  • 2
  • 10
  • 24
  • Time for the good old [not not](https://stackoverflow.com/q/25594231/14277722): `[[not not y for y in x] for x in a]` – Michael Szczesny Jan 27 '22 at 12:54
  • Does this answer your question? [list comprehension replace for loop in 2D matrix](https://stackoverflow.com/questions/25345770/list-comprehension-replace-for-loop-in-2d-matrix) – Tomerikoo Jan 27 '22 at 15:29

3 Answers3

0

Nested for loops is the best I could come up with :/

You would just change the values in the array.

l= [[1,0,1],[1,1,1],[0,0,0]]
for i in range(len(l)):
    for j in range(len(l[i])):
        if l[i][j] == 1:
            l[i][j] = True
        else:
            l[i][j] = False

output: [[True, False, True], [True, True, True], [False, False, False]]

gomer
  • 1
  • First of all, the question specifically asks for a list-comprehension. Second, that `if/else` is really an overkill` - just do `bool(l[i][j])`... – Tomerikoo Jan 27 '22 at 15:30
0

Is a nested list comprehension what you are looking for?

[[bool(inner_entry) for inner_entry in inner_list] for inner_list in outer_list]
PlzBePython
  • 406
  • 2
  • 8
0

You can do something like:

x = [[1, 0, 1], 
     [1, 1, 1], 
     [0, 0, 0]]

y = [[bool(i) for i in x] for x in x]
print(y)

the output is:

>>> [[True, False, True], [True, True, True], [False, False, False]]
Muhammad Mohsin Khan
  • 1,444
  • 7
  • 16
  • 23