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

2024-04-25 06:56:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我几天前就开始学习python了,它的功能和语法灵活性给我留下了深刻的印象,但今天我遇到了一个在其他编程语言中从未见过的奇怪的错误,我想这是由于我对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

Tags: andinselfnodefalseforindexif
1条回答
网友
1楼 · 发布于 2024-04-25 06:56:21

当前代码正在将生成器表达式附加到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值使用三个不同的测试)。你知道吗

相关问题 更多 >