1

I have a list of strings, and I want to replace each 'X' and 'O' with True and False - turning each string into a list of booleans.

arr = ['XOOXO',
       'XOOXO',
       'OOOXO',
       'XXOXO',
       'OXOOO']

temp_list = []
bool_lists =[]

for str in arr:
    for char in str:
        if char == "X":
            temp_list.append(True)
        else:
            temp_list.append(False)
    bool_lists.append(temp_list)
    temp_list = []

This fills up the temp_list variable with booleans, appends the temp_list to the bool_lists variable, then empties the temp_list variable before starting on the next row.

The code above works, but I feel like there must be a more straightforward, pythonic way of doing this.

Timur Shtatland
  • 12,024
  • 2
  • 30
  • 47
Mark Boyd
  • 15
  • 7
  • Example: `bools = [c == "X" for c in "XOOXO"]` yields `[True, False, False, True, False]`. Extend for the `arr` list. – jarmod Mar 21 '23 at 13:55
  • 1
    `bool_lists = [[char == 'X' for char in string] for string in arr]` – Guy Mar 21 '23 at 13:57
  • 1
    See the linked duplicate. Problems like this are a natural fit for list comprehensions. Use the technique twice: for the code the produces a "row" of booleans from a single string, and again to apply that code to each string in the overall list. – Karl Knechtel Mar 21 '23 at 14:00
  • Thank you everyone, I knew it probably had to do something with dict/list comprehension, and I looked around but couldn’t find it. Thanks for pointing it out! – Mark Boyd Mar 21 '23 at 17:48

2 Answers2

1

Use dictionaries and list comprehension like so:

dct = {'X': True, 'O': False}
bool_lists = [[dct[c] for c in s] for s in arr]
print(bool_lists)
# [[True, False, False, True, False], [True, False, False, True, False], [False, False, False, True, False], [True, True, False, True, False], [False, True, False, False, False]]
Timur Shtatland
  • 12,024
  • 2
  • 30
  • 47
0

Try this way, it's more sample

[[{"X":True,"O":False}.get(col, col)  for col in row] for row in arr]