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.
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]]
Try this way, it’s more sample
[[{"X":True,"O":False}.get(col, col) for col in row] for row in arr]
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.
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]]
Try this way, it’s more sample
[[{"X":True,"O":False}.get(col, col) for col in row] for row in arr]