简体   繁体   English

“ TypeError:'int'对象不支持项目分配”; 迭代问题

[英]“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. 我有这个脚本,我需要在其中循环访问列表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. 如果IDLE抱怨我将一个变量分配给str,那是可以理解的(这将是遍历值而不是索引的问题),但是考虑到我没有整数,我不明白为什么会发生此问题。

idx is just an integer like 0 and there is no such thing a 0[0] idx只是一个像0的整数,没有这样的东西0[0]

you want to use val which is your item from your list. 您想使用val,这是您列表中的商品。

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 . enumerate()函数返回一个元组,该元组是(整数,对象)- 有关enumerate的信息,请参见python文档

You are trying to index an integer, which you can't. 您试图索引一个整数,但不能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM