【问题标题】:Add tuple to list of tuples in Python将元组添加到 Python 中的元组列表
【发布时间】:2009-12-10 03:29:54
【问题描述】:

我是 python 新手,不知道最好的方法。

我有一个表示点的元组列表和另一个表示偏移量的列表。我需要一组由此形成的所有组合。 这是一些代码:

offsets = [( 0, 0),( 0,-1),( 0, 1),( 1, 0),(-1, 0)]
points = [( 1, 5),( 3, 3),( 8, 7)]

所以我的组合点应该是

[( 1, 5),( 1, 4),( 1, 6),( 2, 5),( 0, 5),
 ( 3, 3),( 3, 2),( 3, 4),( 4, 3),( 2, 3),
 ( 8, 7),( 8, 6),( 8, 8),( 9, 7),( 7, 7)]

我无法使用 NumPy 或任何其他库。

【问题讨论】:

    标签: python tuples


    【解决方案1】:
    result = [(x+dx, y+dy) for x,y in points for dx,dy in offsets]
    

    欲了解更多信息,请参阅list comprehensions

    【讨论】:

      【解决方案2】:

      很简单:

      >>> rslt = []
      >>> for x, y in points:
      ...     for dx, dy in offsets:
      ...         rslt.append( (x+dx, y+dy) )
      ... 
      >>> rslt
      [(1, 5), (1, 4), (1, 6), (2, 5), (0, 5), (3, 3), (3, 2), (3, 4), (4, 3), (2, 3), (8, 7), (8, 6), (8, 8), (9, 7), (7, 7)]
      

      循环遍历点和偏移,然后构建将偏移添加到点的新元组。

      【讨论】:

        【解决方案3】:

        就个人而言,我喜欢 Alok 的回答。但是,对于itertools 的粉丝来说,基于 itertools 的等价物(在 Python 2.6 及更高版本中)是:

        import itertools as it
        ps = [(x+dx, y+dy) for (x, y), (dx, dy) in it.product(points, offsets)]
        

        但是,在这种情况下,itertools 解决方案比简单的解决方案快(实际上它要慢一点,因为它需要为每个偏移量重复解压缩每个 x, y,而 Alok 的简单方法解压缩每个x, y 但一次)。尽管如此,在其他情况下,itertools.product 是嵌套循环的绝佳替代品,因此,值得了解它!-)

        【讨论】:

        • 另外值得注意的是,组合函数 itertools.product、itertools.permutations 和 itertools.combinations 是 Python 2.6 中的新功能。
        • 好的,完成了(虽然每次提到任何 Python 特性时,解释每个特性引入的 Python 版本会非常烦人,你知道的!-)。
        【解决方案4】:

        如果您不关心结果中的重复:

        result = []
        for ox, oy in offsets:
            for px, py in points:
                result.append((px + ox, py + oy))
        

        如果您确实关心结果中的重复项:

        result = set()
        for ox, oy in offsets:
            for px, py in points:
                result.add((px + ox, py + oy))
        

        【讨论】:

          猜你喜欢
          • 2021-12-27
          • 1970-01-01
          • 2014-04-13
          • 1970-01-01
          • 2020-05-12
          • 1970-01-01
          • 1970-01-01
          • 2018-05-02
          • 2015-05-09
          相关资源
          最近更新 更多