What is the most pythonic way of replacing values in nested lists?

Question:

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.

Asked By: Mark Boyd

||

Answers:

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]]
Answered By: Timur Shtatland

Try this way, it’s more sample

[[{"X":True,"O":False}.get(col, col)  for col in row] for row in arr]
Answered By: 抓老鼠的猪
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.