Python将对象添加到for循环迭代中的每个项目

时间:2018-08-25 17:36:41

标签: python for-loop

几天前,我开始学习python,实际上,它的功能和语法灵活性给我留下了深刻的印象,但是今天,我遇到了一个奇怪的bug,我从未在其他编程语言中见过,我想这是由于我对Python的了解有限而引起的,对于这种行为的任何帮助和解释,我将不胜感激。

我有一个简单的for循环,在其中循环访问节点列表,在每次迭代中,我都将邻居添加到当前节点,但似乎不仅将它们添加到当前节点,而且还添加到集合中的所有其他节点,所以最后我没有拥有最多8个邻居的节点,而最后却拥有(8个*集合中的节点数)邻居的节点,我不知道我在这里错过了什么。

def evaluate_neighbours(nodes):
for node in nodes:
    node.neighbours.append(n for n in nodes if n.x == node.x - 1 and n.y == node.y)
    node.neighbours.append(n for n in nodes if n.x == node.x + 1 and n.y == node.y)
    node.neighbours.append(n for n in nodes if n.y == node.y - 1 and n.x == node.x)
    node.neighbours.append(n for n in nodes if n.y == node.y + 1 and n.x == node.x)
    node.neighbours.append(n for n in nodes if n.y == node.y + 1 and n.x == node.x + 1)
    node.neighbours.append(n for n in nodes if n.y == node.y + 1 and n.x == node.x - 1)
    node.neighbours.append(n for n in nodes if n.x == node.x - 1 and n.y == node.y + 1)
    node.neighbours.append(n for n in nodes if n.x == node.x + 1 and n.y == node.y - 1)

编辑:

生成节点的节点类和代码如下:

class Node:
x = 0
y = 0
neighbours = []
alive = False

def __init__(self, _x, _y, _alive):
    self.x = _x
    self.y = _y
    self.alive = _alive


def generate_grid(data):
nodes = []
for index_y, y in enumerate(data):
    for index_x, x in enumerate(y):
        if x == "X":
            nodes.append(Node(index_x, index_y, True))
        else:
            nodes.append(Node(index_x, index_y, False))
return nodes

1 个答案:

答案 0 :(得分:3)

您当前的代码正在将生成器表达式附加到neighbors列表中。我很确定您要附加实际节点,而不是生成器。此外,由于生成器是闭包(如果您不知道这是什么意思,请不要担心太多),因此在确定要附加的节点时,您的计算可能会出错。

我建议您进行第二次显式循环,而不是使用任何生成器表达式,并在一个if语句中将生成器表达式中具有的所有if子句转换为条件的一部分。看起来像这样:

for node in nodes:
    for n in nodes:
        if (n.x == node.x - 1 and n.y == node.y or
            n.x == node.x + 1 and n.y == node.y or
            ...):
                 node.neighbours.append(n)

我并没有复制所有条件,但是您可以这样做,只需将它们与or连接即可。如果您想简化流程,则可以对某些条件进行分组(例如,您可以测试n.x == node.x - 1 and node.y - 1 <= n.y <= node.y + 1而不是对不同的y值使用三个不同的测试)。