我正在创建代码,用于计算传递坐标的邻居坐标。
我有一个带有";"方向";我想移动到,第一个数字是X值,第二个数字是Y值。
directions = [[0, 1], [0, -1], [1, 0], [-1, 0]]
然后我有一个函数来计算新的坐标并将它们存储在列表"中;结果";
results = []
def NeighborsFinder(coordinate):
originalCoordinate = coordinate
for x in range(0, len(directions)):
coordinate[0] += directions[x][0]
coordinate[1] += directions[x][1]
results.append(coordinate)
print(coordinate)
coordinate = originalCoordinate
示例:如果我通过坐标[2,3]
然后正确的输出应该是带有坐标的列表:[2,4][2,2],[3,3],[1,3]
好吧,但发生在我身上的是,它加+1,但不减-1所以我的输出看起来是这样的:[2,4],[2,3],[3,3]。
好吧,这样代码就不会做你想做的事情。列表是可变的,这意味着
>>> coordinate = [2, 3]
>>> oldCoordinate = coordinate
>>> coordinate.append(5)
>>> coordinate
[2, 3, 5]
>>> oldCoordinate # oldCoordinate has changed too
[2, 3, 5]
一种选择是使用复制
>>> coordinate = [2, 3]
>>> oldCoordinate = coordinate.copy()
>>> coordinate.append(5)
>>> coordinate
[2, 3, 5]
>>> oldCoordinate
[2, 3]
但即使这样,这里也有一些需要更改的地方,因为你的代码很难推理,最好这样做
def NeighborsFinder(coordinate, directions):
newCoordinates = []
for x, y in directions:
newCoordinates.append([coordinate[0] + x, coordinate[1] + y])
print(newCoordinates)
它更短、更漂亮,而且更容易对进行推理
编辑:但实际上,它可以更好,它可以是一个清晰的单行
def neighbors_finder(coordinate, directions):
return [[x + coordinate[0], y + coordinate[0]] for x, y in directions]
您实际上是在修改传递到函数中的列表。为了实现这一点,您需要在分配列表时创建一个.copy()
(否则它只会将变量指向现有列表(:
def NeighborsFinder(coordinate):
originalCoordinate = coordinate.copy()
for x in range(0, len(directions)):
coordinate[0] += directions[x][0]
coordinate[1] += directions[x][1]
results.append(coordinate)
print(coordinate)
coordinate = originalCoordinate.copy()
在这两行中:
坐标[0]+=方向[x][0]
坐标[1]+=方向[x][1]
您已经更改了坐标,这些更改将在以下步骤中保留。你不想那样。
您可以创建原始坐标的副本,并根据副本计算所需的坐标,或者在下一个for循环中,坐标不会更改。或者你可以在每个循环中减去之前加的数字。
这是因为您正在修改坐标。让我们修改您的代码:
def NeighborsFinder(coordinate):
neighbors = []
for x in range(0, len(directions)):
neighbor = [coordinate[0] + directions[x][0], coordinate[1] + directions[x][1]]
results.append(neighbor)
return neighbors
# let's use the function
neighbors = NeighborsFinder([3, 5])
print(neighbors)
另一种方法是遵循您的策略:
results = []
def NeighborsFinder(coordinate):
originalCoordinate = coordinate.copy()
for x in range(0, len(directions)):
coordinate = originalCoordinate.copy()
coordinate[0] += directions[x][0]
coordinate[1] += directions[x][1]
results.append(coordinate)
print(coordinate)
根据@Stef:,这是迄今为止最好的
def NeighborsFinder(coordinate):
neighbors = x,y = coordinate
return [[x+dx, y+dy] for dx,dy in directions]