Skip to main content
 首页 » 编程设计

python之从可迭代的点生成路径

2025年05月04日13落叶

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

执行此操作的最佳方法是什么?

请您参考如下方法:

这是一个使用来自 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)