我怎么知道发电机一开始是否空了?

有没有一种简单的方法可以测试生成器是否没有任何东西,例如peek,hasNext,isEmpty等?



Qyouu
浏览 349回答 3
3回答

红糖糍粑

建议:def peek(iterable):    try:        first = next(iterable)    except StopIteration:        return None    return first, itertools.chain([first], iterable)用法:res = peek(mysequence)if res is None:    # sequence is empty.  Do stuff.else:    first, mysequence = res    # Do something with first, maybe?    # Then iterate over the sequence:    for element in mysequence:        # etc.
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python