本文介绍了检查空条件的python生成器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

python生成器是列表的良好替代品,我希望在其中检查空条件,这是普通生成器无法实现的.我正在尝试编写一个包装器,该包装器将允许检查空条件,但仍然很懒,并提供了生成器的优点.

python generators are good replacements for lists in most cases expect where I would like to check for empty condition which is not possible with plain generators. I am trying to write a wrapper which will allow checking for empty condition but is still lazy and gives the benefit of generators.

class mygen:
  def __init__(self,iterable):
    self.iterable = (x for x in iterable)
    self.peeked = False
    self.peek = None
  def __iter__(self):
    if self.peeked:
      yield self.peek
      self.peeked = False
    for val in self.iterable:
      if self.peeked:
        yield self.peek
        self.peeked = False
      yield val
    if self.peeked:
      yield self.peek
      self.peeked = False
  def __nonzero__(self):
    if self.peeked:
      return True
    try:
      self.peek = self.iterable.next()
      self.peeked = True
      return True
    except:
      return False
  1. 我认为它的行为像普通生成器一样正确.有拐角处的情况吗我丢了?
  2. 这看起来不太优雅.有没有更好的Pythonic方式可以做到这一点?
  1. I think it behaves correctly like a plain generator. Is there any corner caseI'm missing?
  2. This doesn't look elegant. Is there a better more pythonic way of doing the same?

样品用量:

def get_odd(l):
    return mygen(x for x in l if x%2)

def print_odd(odd_nums):
  if odd_nums:
      print "odd numbers found",list(odd_nums)
  else:
      print "No odd numbers found"

print_odd(get_odd([2,4,6,8]))
print_odd(get_odd([2,4,6,8,7]))

推荐答案

我通常不会实现这种方法发电机.有一种惯用的方法如何测试迭代器it筋疲力尽:

I would not usually implement this kindof generator. There is an idiomatic way how to test if a iterator itis exhausted:

try:
    next_item = next(it)
except StopIteration:
    # exhausted, handle this case

用一些特定于项目的LBYL惯用语代替EAFP惯用语令人困惑,根本没有好处.

Substituting this EAFP idiom by some project-specific LBYL idiom seemsconfusing and not beneficial at all.

也就是说,如果我真的想这样做,这就是我将如何执行此操作:

That said, here is how I would implement this if I really wanted to:

class MyIterator(object):
    def __init__(self, iterable):
        self._iterable = iter(iterable)
        self._exhausted = False
        self._cache_next_item()
    def _cache_next_item(self):
        try:
            self._next_item = next(self._iterable)
        except StopIteration:
            self._exhausted = True
    def __iter__(self):
        return self
    def next(self):
        if self._exhausted:
            raise StopIteration
        next_item = self._next_item
        self._cache_next_item()
        return next_item
    def __nonzero__(self):
        return not self._exhausted

这篇关于检查空条件的python生成器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 16:14