在大多数情况下,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
- 我认为它的行为就像一个普通的生成器一样正确。有没有我遗漏的角落案例?
- 这看起来并不优雅。有没有更好的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]))