这里究竟有什么是不可迭代的,以及如何解决它?

What exactly is not iterable here, and how to fix it?

这种问题在这里问了很多,但我还是不知道为什么会出现在这里。错误消息是:

TypeError: 'P' object is not iterable

并由 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 的列表,这些新的 P 离parent,并将所述父对象附加到新对象中的 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是一个列表,所以我们不能使用 + 运算符。我们可以对 list.

使用 append function