【问题标题】:Generating a path from an iterable of points从可迭代的点生成路径
【发布时间】:2012-11-28 23:57:20
【问题描述】:

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

最好的方法是什么?

【问题讨论】:

    标签: python python-3.x iterator iterable


    【解决方案1】:

    这是一个使用来自http://docs.python.org/3/library/itertools.html#itertools-recipespairwise() 配方的示例

    >>> 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】:

      现在我明白了这个问题

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

      【讨论】:

        【解决方案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})))
        

        【讨论】:

          【解决方案4】:

          您可以使用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)]
          

          【讨论】:

            【解决方案5】:

            使用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 的序列按该顺序插入到集合中。

            【讨论】:

            • 我喜欢这个食谱,尽管它比我需要的更通用。我想知道为什么在当前的itertools 文档中这个配方被另一个配方取代了?
            • @max:它被替换为pairwise recipe to illustrate tee。配方用于展示模块的功能,tee() 尚未在该页面上使用。
            猜你喜欢
            • 1970-01-01
            • 2015-07-23
            • 1970-01-01
            • 1970-01-01
            • 2019-08-11
            • 2022-11-30
            • 2020-06-29
            • 1970-01-01
            • 2018-05-16
            相关资源
            最近更新 更多