究竟什么不能在这里迭代,以及如何解决它?

时间:2017-12-25 12:51:15

标签: python python-3.x iterable

这里有很多问题,但我仍然不知道为什么会这样。错误按摩是:

  

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属性。你给我的答案有助于避免错误,但我不知道如何继续

3 个答案:

答案 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 列表,因此我们无法使用 + 运算符。我们可以将追加功能用于列表