假设我有一组{a, b, c, d}
。我想从它创建一个“路径”,这是一个生成(a, b)
的生成器,然后(b, c)
,然后(c, d)
(当然set
是无序的,所以任何其他通过元素的路径是可以接受的。)
这样做的最佳方式是什么?
答案 0 :(得分: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})))
答案 1 :(得分:3)
以下是使用http://docs.python.org/3/library/itertools.html#itertools-recipes
中的pairwise()
食谱的示例
>>> from itertools import tee
>>> def pairwise(iterable):
... "s -> (s0,s1), (s1,s2), (s2, s3), ..."
... a, b = tee(iterable)
... next(b, None)
... return zip(a, b)
...
>>> for pair in pairwise({1, 2, 3, 4}):
... print(pair)
...
(1, 2)
(2, 3)
(3, 4)
答案 2 :(得分: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)
这恰好遵循排序顺序,因为对于python整数hash(x) == x
,因此将1,2,3,4的顺序按顺序插入到集合中。
答案 3 :(得分:0)
您可以使用pairwise
itertools 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)]
答案 4 :(得分:0)
现在我理解了这个问题
from itertools import islice a = {'A','B','C','D'} zip(a,islice(a,1,None)) #[('A', 'C'), ('C', 'B'), ('B', 'D')]