Home > Blockchain >  List to list dictionary (Python optimization)
List to list dictionary (Python optimization)

Time:11-09

I'm trying to convert a list of lists of strings (that represents a tic-tac-toe game) to a list of lists of integers, so that I can perform calculations.

These are the possible inputs:

A = ['X', 'O', '#']

And these the corresponding integers:

B = [1, 0, 99]

So overall it would do the following:

[['X', 'O', 'O'], ['O', 'X', 'O'], ['O', '#', 'X']] -> [[1, 0, 0], [0, 1, 0], [0, 99, 1]]

I have created the following functions to perform this translation, but I'm sure there must be a faster and more efficient way:

def make_integer_matrix(inputs):
    A = ['X', 'O', '#']
    B = [1, 0, 99]
    integer_matrix = []
    #First translate to integers
    for row in inputs:
        row_new = [B[A.index(row[0])], B[A.index(row[1])], B[A.index(row[2])]]
        integer_matrix.append(row_new)
    return integer_matrix

CodePudding user response:

Consider creating a mapping dictionary and using a nested list comprehension:

>>> mapping = {'X': 1, 'O': 0, '#': 99}
>>> raw_board = [['X', 'O', 'O'], ['O', 'X', 'O'], ['O', '#', 'X']]
>>> value_board = [[mapping[c] for c in row] for row in raw_board]
>>> value_board
[[1, 0, 0], [0, 1, 0], [0, 99, 1]]

CodePudding user response:

Instead of constantly searching the first array to determine the corresponding index, create a dictionary from the two lists and use that for the translation:

A = ['X', 'O', '#']
B = [1, 0, 99]
# create translation table from lists
translations = dict(zip(A, B))

for row in inputs:
    row_new = [translations[v] for v in row]
    integer_matrix.append(row_new)
return integer_matrix

CodePudding user response:

A = ['X', 'O', '#']
B = [1, 0, 99]

game_map = [['X', 'O', 'O'], ['O', 'X', 'O'], ['O', '#', 'X']]


def map_values(A, B):
    result_dict = dict()
    for a, b in zip(A, B):
        result_dict[a] = b
    
    return result_dict

char_to_int_map = map_values(A, B)

game_map_int = [[char_to_int_map[x] for x in row] for row in game_map]

print(game_map_int)
  • Related