Python有一个alternative ^{} signature,它将函数作为第一个参数,并将确定停止条件的sentinel作为第二个参数。在
使用它,你可以想出这样的东西:for s,img in iter(cv.read, (False, None)):
print img
不过,我怀疑它是否比在if块中使用普通break更好。在
而且,它只接受sentinel作为整体返回值,不能将stop条件建立在它的某个部分上(例如,基于元组的第一个值)。这可以解决问题,但会使代码更加模糊:
^{pr2}$
它使用^{}来确定返回元组的第一个值何时等于False。在
测试的完整版本:>>> class Capture(object):
def __init__(self):
self.L = iter([1,2,3,4,5])
def read(self):
try:
img = self.L.next()
except StopIteration:
return (False,None)
return True, img
>>> cv = Capture()
>>> for s,img in iter(cv.read, (False, None)):
print img
1
2
3
4
5
>>> cv = Capture()
>>> for s,img in itertools.takewhile(lambda x: x[0], iter(cv.read, None)):
print img
1
2
3
4
5