How to group two indexes in a tuple?

Asked

Viewed 34 times

0

I want to group two indices that are received from positions that are results of if’s/Elif’s

def MakeListOfFreeFields(board):
    n_rows = len(board)
    n_cols = len(board[0])
    tfields = ()

    for row in range(n_rows):
        for column in range(n_cols):
            if board[row][column] == '1':
                tfields += ([row],[column])
            elif board[row][column] == '2':
                tfields += ([row],[column])
            elif board[row][column] == '3':
                tfields += ([row],[column])
            elif board[row][column] == '4':
                tfields += ([row],[column])
            elif board[row][column] == '5':
                tfields += ([row],[column])
            elif board[row][column] == '6':
                tfields += ([row],[column])
            elif board[row][column] == '7':
                tfields += ([row],[column])
            elif board[row][column] == '8':
                tfields += ([row],[column])
            elif board[row][column] == '9':
                tfields += ([row],[column])
    print(tfields)

O resultado desse print é: 
([0], [0], [0], [1], [0], [2], [1], [0], [1], [1], [1], [2], [2], [0], [2], [1], [2], [2])

E eu gostaria que fosse:
([0][0], [0][1], [0][2], [1][0], [1][1], [1][2], [2][0], [2][1], [2][2])

1 answer

0

If your intention is to retrieve a list of tuples that represent the coordinates of the board that are not filled in, follow an equivalent code capable of solving your problem:

def MakeListOfFreeFields(board):
    ret = []
    for x, row in enumerate(board):
        for y, col in enumerate(row):
            if not col.isdigit():
                ret.append((x, y))
    return ret

tabuleiro = [
    ['1',' ','3'],
    [' ','5',' '],
    ['7',' ','9']
]

saida = MakeListOfFreeFields(tabuleiro)

print(saida)

Exit:

[(0, 1), (1, 0), (1, 2), (2, 1)]

Simplifying your code using a generating function:

def MakeListOfFreeFields(board):
    for x, row in enumerate(board):
        for y, col in enumerate(row):
            if not col.isdigit():
                yield (x, y)

tabuleiro = [
    ['1',' ','3'],
    [' ','5',' '],
    ['7',' ','9']
]

saida = list(MakeListOfFreeFields(tabuleiro))

print(saida)

Exit:

[(0, 1), (1, 0), (1, 2), (2, 1)]

The exit you’re waiting for represents an empty board, look at this:

def MakeListOfFreeFields(board):
    for x, row in enumerate(board):
        for y, col in enumerate(row):
            if not col.isdigit():
                yield (x, y)

tabuleiro = [
    [' ',' ',' '],
    [' ',' ',' '],
    [' ',' ',' ']
]

saida = list(MakeListOfFreeFields(tabuleiro))

print(saida)

Exit:

[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]

Browser other questions tagged

You are not signed in. Login or sign up in order to post.