gpt4 book ai didi

python - 我如何知道生成器是否从一开始就为空?

转载 作者:IT老高 更新时间:2023-10-28 21:05:03 24 4
gpt4 key购买 nike

是否有一种简单的方法来测试生成器是否没有项目,例如 peekhasNextisEmpty 等类似的东西?

最佳答案

建议:

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.

关于python - 我如何知道生成器是否从一开始就为空?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/661603/

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