2014-03-30 29 views
0
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無法打印列表「int」對象不可迭代

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 

然後我試圖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 

有人能告訴我這是爲什麼錯誤?

+0

你是如何創建你正在複製的原始'A'的? – merlin2011

+0

「TypeError:'int'object is not utterable」? 「用語言來」?真? – Johnsyweb

回答

0

我想,你沒有正確複製這個列表。

您最初的名單看起來是這樣的:

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

當您複製它,你創建一個名爲紐瓦新的列表:

[] 

,你只是元素添加到它:

[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] 
0

您的功能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) 

打印此:

[[1, 1, 0], [0, 1, 1]] 
[1, 1, 0, 0, 1, 1] 

正如你看到它不包含子列表,所以它會試圖遍歷整數。

我用copy.deepcopy會做這個工作。

0

您沒有提供了足夠的代碼來重現該問題,但我可以告訴你是什麼錯誤表示。這意味着,在表達式for col in row:中,row實際上是int而不是某種iterable類型。

1

這裏是我的解決方案,這是我測試:

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

如果不做作業,使用copy.deepcopy()

import copy 
b = copy.deepcopy(a) 
0

試圖運行這一點,並注意到,有在結束一個逗號增量語句在CreateBoard中:

row += createOneRow(width), 

這在CopyA方法中丟失時遞增紐瓦。我試圖給這些行添加一個逗號,並且沒有錯誤。

+0

給主持人的說明:我以前的回答有這樣的觀察,這可能會幫助提問的人以及關於「,」意味着什麼的問題。你應該單獨編輯問題而不是刪除整個問題。 – haraprasadj