这里有很多问题,但我仍然不知道为什么会这样。错误按摩是:
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
属性。你给我的答案有助于避免错误,但我不知道如何继续
答案 0 :(得分:2)
两个问题:
首先,您正尝试通过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])
。
答案 1 :(得分:0)
您实际上是在以下行收到此错误:
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->)
]
答案 2 :(得分:0)
试试这个:
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 是列表,因此我们无法使用 + 运算符。我们可以将追加功能用于列表。