0

I have following code:

# dict for replacements
replacements = {'*': 0, ' ': 1, 'A': 2, 'B': 3}
# open and read file
file = open(file, "r")
lines = file.readlines()
file.close()
# row and col count
rows = len(lines)
cols = len(lines[0]) - 1
# create array
maze_array = np.zeros((rows, cols), dtype=str)
# add lines to array
for index, line in enumerate(lines):
    for i in range(0, len(line) - 1):
        maze_array[index][i] = line[i]
return maze_array

This opens a file where the content is just '*', ' ', 'A' or 'B'. From that file I read the lines and get the number of rows as well as columns. Then I create a pseudo array where I add the lines to get following output:

[['*' ' ' '*' ... '*' ' ' '*']
['*' ' ' '*' ... ' ' 'B' '*']
['*' '*' '*' ... '*' '*' '*']]

When I print out the variable lines above, I get following output:

['*****************************************************************\n', '...']

Now my goal is to replace the '*', ' ', 'A' or 'B' with the values from the dictionary (0, 1, 2 or 3). How can I reach my goal?

2 Answers 2

2

You can use a list comprehension. Below is an example

lst = [['*', ' ', '*', '*', ' ', '*'],
       ['*', ' ', '*', ' ', 'B', '*'],
       ['*', '*', '*','*', '*', '*']]

replacements = {'*': 0, ' ': 1, 'A': 2, 'B': 3}

new_lst = [[replacements[i] for i in sublst] for sublst in lst]
# [[0, 1, 0, 0, 1, 0], [0, 1, 0, 1, 3, 0], [0, 0, 0, 0, 0, 0]]
Sign up to request clarification or add additional context in comments.

Comments

1

When assigning the characters to the array, attempt to get the corresponding replacement value:

for index, line in enumerate(lines):
    for i in range(0, len(line) - 1):
        maze_array[index][i] = replacements.get(line[i], line[i])

The dict.get is used with the default value as the character itself so that if a character that has no replacement is encountered, the program will continue normally.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.