简体   繁体   中英

How to replace elements in list/array with dictionary values?

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?

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]]

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM