代码之家  ›  专栏  ›  技术社区  ›  porton

从迭代器(python)中排除第一个元素

  •  1
  • porton  · 技术社区  · 7 年前

    我有发电机功能 A .

    例如(实际上我有一个更复杂的函数 )

    def A():
        yield from [i**2 for i in range(20)]
    

    编写另一个生成器函数 B ,我要枚举 返回第一个元素以外的元素。

    是什么 简洁的 在Python3中实现这一点的方法?

    3 回复  |  直到 7 年前
        1
  •  3
  •   rafaelc    7 年前

    next(it)


    • StopIteration
    • except StopIteration: raise SomethingElse()
    • next(it, None)

    itertools

    def pairwise(iterable):
        "s -> (s0,s1), (s1,s2), (s2, s3), ..."
        a, b = tee(iterable)
        next(b, None)
        return zip(a, b)
    

    b iterable next(b, None)


    def skip_first(iterable):
        it = iter(iterable)
        next(it, None)
        return it
    

    def skip_first(iterable):
        it = iter(iterable)
        next(it, None)
        yield from it
    

    itertools.islice

    it = skip_first(it)
    it = itertools.islice(it, 1, None)
    

    consume

    def consume(iterator, n=None):
        "Advance the iterator n-steps ahead. If n is None, consume entirely."
        # Use functions that consume iterators at C speed.
        if n is None:
            # feed the entire iterator into a zero-length deque
            collections.deque(iterator, maxlen=0)
        else:
            # advance to the empty slice starting at position n
            next(islice(iterator, n, n), None)
    

    None n islice next iterator

        2
  •  7
  •   Patrick Haugh    7 年前

    itertools.islice

    itertools.islice(generator,1,None)
    
        3
  •  1
  •   rafaelc    7 年前

    免责声明:见上文@abarnet和@solaxun的回答。

    只是觉得应该提到以下几点

    如果你有,例如 original = iter((1,2,3,4,5))

    然后

    first, remaining = next(original), original
    

    哪里 remaining 是没有第一个元素的迭代器。