在Python中将元组添加到元组列表中

18

我是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或任何其他库。

4个回答

33
result = [(x+dx, y+dy) for x,y in points for dx,dy in offsets]

更多信息,请参见列表推导式


15
很简单:
>>> 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)]

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


8

个人而言,我喜欢Alok的答案。但是,对于itertools的粉丝来说,在Python 2.6及以上版本中,基于itertools的等效方法是:

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是嵌套循环的绝佳替代品,因此,值得了解!-)


值得注意的是,在Python 2.6中,组合函数itertools.product、itertools.permutations和itertools.combinations是新的。 - musicinmybrain
好的,完成了(虽然每次提到任何Python功能时都要解释该功能是在哪个Python版本中引入的,这真的很烦人,你知道的!-)。 - Alex Martelli

5

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

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))

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接