我正在尝试编写一个函数,它接受一个元组(表示平面中的整数坐标)并返回所有相邻坐标,不包括原始坐标。你知道吗
def get_adj_coord(coord):
'''
coord: tuple of int
should return set of tuples representing coordinates adjacent
to the original coord (not including the original)
'''
x,y = coord
range1 = range(x-1, x+2)
range2 = range(y-1, y+2)
coords = {(x,y) for x in range1 for y in range2} - set(coord)
return coords
问题是此函数的返回值始终包含原始坐标:
In [9]: get_adj_coord((0,0))
Out[9]: {(-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 0), (0, 1), (1, -1), (1, 0), (1, 1)}
我可能缺少一些基本的集合和/或元组,但是下面的函数肯定不会返回我所期望的结果。我还尝试使用:
coords = {(x,y) for x in range1 for y in range2}.remove(coord)
但是函数什么也不返回。有人能指出我在这里非常清楚地遗漏了什么吗?你知道吗
那是因为你没有减去正确的集合对象。当前的方法使用
set((0,0)) -> {0}
将元组强制转换为一个集合。 但是,您需要的是集合中的元组:相关问题 更多 >
编程相关推荐