无法打印list“int”object not iterab

2024-10-03 06:23:49 发布

您现在位置:Python中文网/ 问答频道 /正文

def createOneRow(width):
    """ returns one row of zeros of width "width"...  
         You should use this in your
         createBoard(width, height) function """
    row = []
    for col in range(width):
        row += [0]
    return row


def createBoard(width,height):
    """creates a list
    """
    row = []
    for col in range(height):
        row += createOneRow(width),
    return row


import sys

def printBoard(A):
    """ this function prints the 2d list-of-lists
        A without spaces (using sys.stdout.write)
    """
    for row in A:
        for col in row:
            sys.stdout.write(str(col))
        sys.stdout.write('\n')

以上是基本函数,然后我被要求执行一个复制函数来跟踪原始A。在

^{pr2}$

然后我试图printBoard(newA),但错误出现了:

Traceback (most recent call last):
  File "<pyshell#37>", line 1, in <module>
    printBoard(newA)
  File "/Users/amandayin/Downloads/wk7pr2/hw7pr2.py", line 35, in printBoard
    for col in row:
TypeError: 'int' object is not utterable

有人能告诉我为什么这是个错误吗?在


Tags: ofinfordefstdoutsyscolthis
3条回答

您的函数copy不正确。此代码:

def copy(A):
    height=len(A)
    width=len(A[0])
    newA=[]
    row=[]
    for row in range(0,height):
        for col in range(0,width):
            if A[row][col]==0:
               newA+=[0]
            elif A[row][col]==1:
                newA+=[1]
    return newA

a = [
  [1, 1, 0],
  [0, 1, 1],
]

print a

print copy(a)

打印此:

^{pr2}$

如您所见,它不包含子列表,因此它尝试迭代整数。在

我用copy.deepcopy就可以了。在

这是我的解决方案,我测试过:

def copy(a):
    return [row[:] for row in a]

如果这不是家庭作业,请使用copy.deepcopy()

^{pr2}$

我想你没有正确地复制名单。在

原始列表如下所示:

[[1,2,3],[4,5,6],[7,8,9]]

复制时,将创建一个名为newA的新列表:

^{pr2}$

你只需添加元素:

[1,2,3,4,5,6,7,8,9]

所以你的列表格式不同。在

这也许就是你想要的:

newA=[]
row=[]
for row in range(0,height):
    newRow = []
    for col in range(0,width):
        if A[row][col]==0:
           newRow+=[0]
        elif A[row][col]==1:
            newRow+=[1]
    newA += [newRow]

相关问题 更多 >