我在Python中有一个生成器,如果它有项目我想循环它,如果它是空的则执行不同的操作。像
这样的东西if generator is empty:
perform some action
else:
for item in generator:
perform some actions
我知道没有办法判断一个生成器是否为空而没有迭代它,但似乎仍然应该有一些很好的方法来执行这个逻辑。我能想到的最好的东西是https://stackoverflow.com/a/664239/161801,这看起来非常不优雅,我猜是因为它必须将发电机的第一个元素与其余元素分开处理。
答案 0 :(得分:3)
如果生成器不为空,只需设置一个标志:
isGeneratorEmpty = True
for item in generator:
isGeneratorEmpty = False
perform some actions
if isGeneratorEmpty:
perform some actions