简体   繁体   中英

Tuple index out of range python

start = [0,0,0,0,0,0,0,0,0]
def print_board(turn, board):
    print(turn + " turn" + "\n   {}{}{}\n   {}{}{}\n   {}{}{}".format(board))
current_turn = "your"
print_board(current_turn, start)

The above stuff gives

Traceback (most recent call last):
  File "so.py", line 5, in <module>
    print_board(current_turn, start)
  File "so.py", line 3, in print_board
    print(turn + " turn" + "\n   {}{}{}\n   {}{}{}\n   {}{}{}".format(x for x in board))
IndexError: tuple index out of range

I've got 9 values in my tuple or list and 9 curly brackets. Right?

The format method expects individual arguments rather than a single list. But you can easily fix it by changing:

"...".format(board)

to:

"...".format(*board)

The asterisk * will cause the list elements to be passed as individual arguments.

You have only one item in the values list for the print -- a list. You need to split out the individual integers.

def print_board(turn, board):
    print(turn + " turn" + "\n   {}{}{}\n   {}{}{}\n   {}{}{}".format(
        board[0], board[1], board[2],
        board[3], board[4], board[5],
        board[6], board[7], board[8]
    ))

I don't think 'format' works like that with lists. You would need something like this I believe.

x=[1,2]
print('one + {} = {}'.format(x[0],x[1]))

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