简体   繁体   中英

Python TypeError:unsupported operand type(s) for +: 'int' and 'list'

n = 2
board = [[0] * 2 ** n for i in range(2 ** n)]
rr = 1
rc = 1
currentNum=0

if n == 2:
    for i in board:
        for j in board:
            if board[rr + i][rc + j] == 0:
                board[rr + i][rc + j] = currentNum
    currentNum + 1

I am getting an error that says: unsupported operand type(s) for +: 'int' and 'list'

I don't know much python but that should get i and j for the board like position Board[rr+i][rc+j] is there another way I should be doing this in python?

Edit: asked to post complete traceback

Traceback (most recent call last):
  File "C:/Users/***/PycharmProjects/***/***.py", line 10, in <module>
    if board[rr + i][rc + j] == 0:
TypeError: unsupported operand type(s) for +: 'int' and 'list'

Are you from a C/C++ background? Normally in those languages you'd do for loops like: for (int i = 0; i < n; i++) , and each value of i would be the index.

In Python, however, when you do a for-loop you're iterating through each value of board . So in this case, i is actually each sublist in board .

You probably want to do:

for i in range(n):
    for j in range(n):
        ...

In your code, i is a sublist in board . And rr is an int, so when you try to do rr + i ,you will get the error unsupported operand type(s) for +: 'int' and 'list' .To get every index in board ,you can use

for i in range(len(board)):
    .....

I think you want this:

n = 2
board = [[0] * 2 ** n for i in range(2 ** n)]
rr = 1
rc = 1
currentNum=0

if n==2:
    for i in range(len(board)):
        for j in range(len(board[i])):
            if board[i][j] == 0:
                board[i][j] = currentNum
            currentNum+=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