Python 两组元组之间的差异

Python 两组元组之间的差异,python,Python,我正在尝试编写一个函数,它接受一个元组(表示平面中的整数坐标),并返回所有相邻坐标,不包括原始坐标 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 = c

我正在尝试编写一个函数,它接受一个元组(表示平面中的整数坐标),并返回所有相邻坐标,不包括原始坐标

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}
将元组强制转换为一个集合。 但是,您需要的是集合中的元组:

coords = {(x,y) for x in range1 for y in range2} - {coord}

那是因为你没有减去正确的集合对象。您当前的方法使用
set((0,0))->{0}
将元组强制转换为一个集合。 但是,您需要的是集合中的元组:

coords = {(x,y) for x in range1 for y in range2} - {coord}

set(coord)
-->
set(coord,)
@cᴏʟᴅsᴘᴇᴇᴅ 谢谢非常感谢。
set(coord)
-->
set(coord,)
@cᴏʟᴅsᴘᴇᴇᴅ 谢谢非常感谢。啊,我是个白痴。谢谢你指出这一点。一定是时候出去休息一下了……啊,我是个白痴。谢谢你指出这一点。一定是时候出去休息一下了。。。