简体   繁体   English

如何获得可迭代的最后n个值以外的所有值

[英]How to get all but the last n values of iterable

def drop(iterable, n):
    iterator = iter(iterable)
    iter_list = []
    
    try:
        while True:
            it = next(iterator)
            if len(iter_list) <= n:
                iter_list.append(it)
                yield it
    except StopIteration:
        pass

I'm suppose to produce all values from the iterable except for the last n values.我想从迭代中生成除最后 n 个值之外的所有值。 Right now, I have it so that it produces at most n values.现在,我拥有它,因此它最多产生 n 个值。 How do I do it so that it's the other way around?我该怎么做才能让它反过来? I'd like to keep the same structure if I can.如果可以的话,我想保持相同的结构。

I'm not allowed to count the number of values the iterable produces.我不允许计算可迭代产生的值的数量。 I also can't use itertools or call len, index, slice, etc on the iterable.我也不能在可迭代对象上使用 itertools 或调用 len、index、slice 等。

from collections import deque

def drop(it, n):
    queue = deque()
    for _ in range(n):
      queue.append(next(it))
    while True:
      # If next(it) throws a StopIteration, we need a little bit more
      # code here to indicate this iterable if finished.
      queue.append(next(it))
      yield queue.popleft()

I probably need to add a couple of try/except StopIteration to get it running perfectly, but this is the basic idea.我可能需要添加一些 try/except StopIteration 才能让它完美运行,但这是基本思想。

you have 2 options here first is to generate the whole iterable and drop the last n, and in the while loop you return every value from the start or the more clever way of using a buffer of n values.您首先在这里有 2 个选项是生成整个可迭代对象并删除最后一个 n,并且在 while 循环中您从开始或使用 n 值缓冲区的更聪明的方式返回每个值。 Just a slight modification to your code will do the trick只需对您的代码稍作修改即可解决问题

def drop(iterable, n):
   iterator = iter(iterable)
   iter_list = []

   try:
        while True:
            it = next(iterator)
            iter_list.append(it)
            if len(iter_list) > n:
                element = iter_list.pop(0)
                yield element
   except StopIteration:
        pass

Here every new element is appended in the while loop and the condition to yield elements runs after the first n elements are generated.这里每个新元素都附加到 while 循环中,并且在生成前 n 个元素之后运行产生元素的条件。 Then the first generated element is yielded, and so on with n elements generated always.然后生成第一个生成的元素,以此类推,始终生成 n 个元素。 When the iterator has no more to give the exception is raised and the while loop stops withholding the last n elements that are never returned当迭代器没有更多可以给出异常时,会引发异常并且 while 循环停止保留从未返回的最后 n 个元素

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM