我不明白如何列表不能迭代。我们初始化了这个列表并用它在列表中添加了拼图游戏。为什么我得到这个错误“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)而不是整个代码。此外,总是包含回溯,以便我们至少可以查看问题发生的位置。虽然从错误中应该很清楚,你实际上并没有在列表上迭代。运行调试器并找出它为什么崩溃。 –