简体   繁体   中英

“TypeError: 'int' object does not support item assignment”; iteration issue

def create_board():
    b = [[['',''] for i in range(8)] for j in range(8)]
    return b
game_board = create_board()


for i in game_board[0]:
    for idx, val in enumerate(i[1::2]):
        idx[0] = 0
        idx[1] = 0
print game_board

I have the this script, in which I need to iterate through the first list that is within the list game_board. Starting at the second element I need to change the values in every other element's list. However when I run this I am greeted with the error

idx[0] = 0
TypeError: 'int' object does not support item assignment

It would be understandable if IDLE was complaining about me assigning a variable to a str, (which would be an issue with iterating over values rather than indices), but i can't see why this problem is happening considering I have no integers.

idx is just an integer like 0 and there is no such thing a 0[0]

you want to use val which is your item from your list.

actually it looks like you have other problems ...

fixed

for row in game_board:
    for item in row:
        item[0] = 0
        item[1] = 0

The enumerate() function returns a tuple that is (integer, object) -- see the python documenation for enumerate .

You are trying to index an integer, which you can't.

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