2009-12-10 160 views
16

我是python的新手,不知道这是做什么的最好方法。将元组添加到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的或任何其他库。

回答

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

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

14

很简单:

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

循环通过点和偏移量,然后建立添加偏移点的新的元组。

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

就个人而言,我喜欢阿洛克的答案。然而,对于itertools球迷,基于itertools等效(在Python 2.6和更高版本):

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

然而,在这种情况下,迭代工具解决方案比简单的一快(它实际上是一点点因为它需要对每个偏移量重复解压每个x, y,而Alok的简单方法是将每个x, y解开,但是一次)。但是,在其他情况下,itertools.product是嵌套循环的极好选择,所以值得了解! - )

+0

还值得注意的是,组合函数itertools.product,itertools.permutations和itertools.combinations是Python 2.6中的新增功能。 – musicinmybrain 2009-12-10 05:50:13

+0

好了,完成了(尽管解释Python每次发布每个功能的过程都很麻烦,每次提到任何Python功能时,都知道!)。 – 2009-12-10 06:00:48