我不明白如何列表不能迭代。我們初始化了這個列表並用它在列表中添加了拼圖遊戲。爲什麼我得到這個錯誤「TypeError:'方法'對象不可迭代」?
用戶將輸入他們想要的電路板的行數和列數。每一行都是一個新的作品,每一列都是一個新的作品。每一塊是3列表看起來像一個矩陣。我的想法是創建一個列表pieces = [],並將每個新生成的片段追加到列表中。
我的問題是,我不能得到str()打印板。我認爲我們應該在件數列表中列出每件作品的3個列表的第一個列表,然後列出3個列表的中間列表,然後列出三個列表的最後列表。並從一條新線開始。我知道如何實現它。
或者我想我可以單獨打印每一個部分,然後添加件到該字符串打印出板。所以我不會使用pieces = []列表。我不知道哪個最好或如何實施。
我試圖尋找其他的問題,但我無法找到一個答案,我嘗試打印類的字符串表示:
from random import randint
from pprint import pprint
class Jigsaw:
def __init__(self, r, c):
self.pieces = []
self.row = r
self.col = c
def __str__(self):
"""
Writes the state and value to a string.
"""
s =" "
d = ""
f = ""
g = ""
for row in self.pieces:
#print(row)
for col in row:
#print(col)
d = d +" "+ format(col[0])
print(d)
for row in self.pieces:
#print(row)
for col in row:
#print(col)
f = f +" " + format(col[1])
print(f)
for row in self.pieces:
#print(row)
for col in row:
#print(col)
g = g +" "+ format(col[2])
print(g)
# return pce
# result = 'ball : %s' \
# % (pce)
#return r
def __repr__(self):
"""
Returns the string representation.
"""
return str(self)
def puzzle_board(self):
for c in range(self.row):
for d in range(self.col):
self.pieces.append(self.add_piece)
return self.pieces
def add_piece(self):
a = PieceGenerator()
b = self.a_piece(a.idn,a.top,a.left,a.right,a.bottom)
self.pieces.append(b)
return(b)
def mis(self):
self.add_piece()
# def boardShuffle(self,board):
def a_piece(self, id, top,left,right,bottom):
"""
Returns the piece values.
"""
pce = [[" ", top, " "], [left, id, right], [" ", bottom, " "]]
return(pce)
# def puzzleSolve(self,board):
class PieceGenerator:
"""
Creates new puzzle pieces with their values.
"""
idn = 0 #Global variable to keep track of all the pieces
def __init__(self):
"""
A piece have top, bottom, right, left values and puzzle piece it self
"""
self.top = randint(10,99)
self.bottom = randint(10,99)
self.right = randint(10,99)
self.left = randint(10,99)
PieceGenerator.idn += 1
print(Jigsaw(3,5).puzzle_board())
這裏是我的錯誤:
Traceback (most recent call last):
File "C:/Users/HP/PycharmProjects/untitled/.idea/jigsaw.py", line 102, in <module>
print(Jigsaw(3,5).puzzle_board())
File "C:/Users/HP/PycharmProjects/untitled/.idea/jigsaw.py", line 56, in __repr__
return str(self)
File "C:/Users/HP/PycharmProjects/untitled/.idea/jigsaw.py", line 22, in __str__
for col in row:
TypeError: 'method' object is not iterable
請發佈[MCVE](http://stackoverflow.com/help/mcve)而不是整個代碼。此外,總是包含回溯,以便我們至少可以查看問題發生的位置。雖然從錯誤中應該很清楚,你實際上並沒有在列表上迭代。運行調試器並找出它爲什麼崩潰。 –