2012-12-11 52 views
1

假设我有一组集合{a, b, c, d}。我想从它创建一个“路径”,这是一个生成(a, b),然后(b, c),然后(c, d)(当然set是无序的,所以通过元素的任何其他路径是可以接受的)的生成器。从可迭代的点生成路径

这样做的最好方法是什么?

回答

2

使用Rolling or sliding window iterator in Python溶液:

>>> from itertools import islice 
>>> def window(seq, n=2): 
...  "Returns a sliding window (of width n) over data from the iterable" 
...  " s -> (s0,s1,...s[n-1]), (s1,s2,...,sn), ...     " 
...  it = iter(seq) 
...  result = tuple(islice(it, n)) 
...  if len(result) == n: 
...   yield result  
...  for elem in it: 
...   result = result[1:] + (elem,) 
...   yield result 
... 
>>> path = window({1, 2, 3, 4}) 
>>> for step in gen: 
...  print path 
(1, 2) 
(2, 3) 
(3, 4) 

这发生遵循排序的顺序,因为对于蟒整数hash(x) == x因此1,2,3,4插入以该顺序进入集的序列。

+0

我喜欢这个食谱,尽管它比我需要的更一般。我想知道为什么这个配方在当前的'itertools'文档中被替换为另一个? – max

+0

@max:它被替换为['pairwise'配方来说明'tee'](http://hg.python.org/cpython/rev/ea058504104c)。这里的配方是为了炫耀模块的功能,'tee()'还没有在这个页面上使用。 –

3
def gen(seq): 
    it = iter(seq) 
    a, b = next(it), next(it) 
    while True: 
    yield (a, b) 
    a, b = b, next(it) 

print(list(gen({1, 2, 3, 4}))) 
0

使用pairwise()配方为例,用户可以使用pairwiseitertools recipe

>>> from itertools import tee 
>>> def pairwise(iterable): 
     a, b = tee(iterable) 
     next(b, None) 
     return zip(a, b) 

>>> pairwise({1, 2, 3, 4}) 
<zip object at 0x0000000003B34D88> 
>>> list(_) 
[(1, 2), (2, 3), (3, 4)] 
0

现在我明白的问题

 
from itertools import islice 
a = {'A','B','C','D'} 
zip(a,islice(a,1,None)) 
#[('A', 'C'), ('C', 'B'), ('B', 'D')]