gpt4 book ai didi

带有检查空条件的 python 生成器

转载 作者:太空狗 更新时间:2023-10-29 18:04:02 26 4
gpt4 key购买 nike

在大多数情况下,python 生成器是列表的良好替代品,除了我想检查空条件的地方,这对于普通生成器来说是不可能的。我正在尝试编写一个包装器,它允许检查空条件但仍然很懒惰并提供生成器的好处。

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 方式来做同样的事情?

示例用法:

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筋疲力尽:

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

用一些特定于项目的 LBYL 惯用语替换这个 EAFP 惯用语似乎令人困惑且毫无益处。

也就是说,如果我真的想要的话,我将如何实现它:

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 生成器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11467430/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com