这里有很多问题,但我仍然不知道为什么会发生这种情况。错误按摩是:
TypeError:'P'对象不可迭代
并由来自for p in self.parents:
的__str__
援引
为什么P
不可迭代?
class P:
limit = 8
def __init__(self,x=0,y=0,p=None):
self.x = x
self.y = y
self.parents = p
def __str__(self):
s = ''
for p in self.parents:
s += '({},{}->)'.format(p.x,p.y)
s += '({},{}->)'.format(self.x,self.y)
return s + '\n'
def next_move(self):
def valid(x):
return x >= 0 and x < P.limit
x,y = self.x,self.y
a = [-1,1]
b = [-2,2]
ls = [(x+i, y+j) for i in a for j in b if valid(x+i) and valid(y+j)]
ls +=[(x+i, y+j) for i in b for j in a if valid(x+i) and valid(y+j)]
to_return = []
for i in range(len(ls)):
to_return += P(ls[i][0],ls[i][1],self)
return to_return
p = P()
print (p.next_move())
编辑:我的问题不是如何删除错误(使用append
),但如何使用next_move()
创建一个新的P
列表,这是一个马移动(国际象棋)远离父母,并附加所述父母到parents
新对象中的属性。你给我的答案有助于避免错误,但我不知道如何继续
两个问题:
首先,您正尝试通过P
将+=
实例添加到列表中。但+=
列表大致对应extend
并采用可迭代:
for i in range(len(ls)):
to_return += [P(...)]
# OR
# to_return.append(P(...))
其次,当您使用P(ls[i][0], ls[i][1], self)
调用构造函数时,您将self
作为p
参数传递,该参数应该是可迭代的。您可能想要使用P(ls[i][0], ls[i][1], [self])
。
您实际上是在以下行中收到此错误:
to_return += P(ls[i][0],ls[i][1],self)
这是因为你应该像这样追加to_return
to_return.append(P(ls[i][0],ls[i][1],self))
或者,如果您有任何特殊原因,请执行以下操作:
to_return += [P(ls[i][0],ls[i][1],self)]
另外,你作为参数传递的self
也不是可迭代的。然后你会在__str__
中遇到问题,如果它被调用的话。
to_return.append(P(ls[i][0], ls[i][1], [self]))
最后,我相信你的意思是__repr__
而不是__str__
,所以你打印:
[(0,0->)(1,2->)
, (0,0->)(2,1->)
]
试试这个:
class P:
limit = 8
def __init__(self, x=0, y=0, p=None):
self.x = x
self.y = y
self.parents = p
def __str__(self):
s = ''
for p in self.parents:
s += '({},{}->)'.format(p.x, p.y)
s += '({},{}->)'.format(self.x, self.y)
return s + '\n'
def next_move(self):
def valid(x):
return 0 <= x < P.limit
x, y = self.x, self.y
a = [-1, 1]
b = [-2, 2]
ls = [(x + i, y + j) for i in a for j in b if valid(x + i) and valid(y + j)]
ls += [(x + i, y + j) for i in b for j in a if valid(x + i) and valid(y + j)]
to_return = []
for i in range(len(ls)):
to_return.append(P(ls[i][0], ls[i][1], self))
return to_return
p = P()
print(p.next_move())
见第27行的变化
因为to_return是一个列表,所以我们不能使用+运算符。我们可以使用追加功能列表。