循环遍历空迭代器不会引发异常 [英] Loop over empty iterator does not raise exception

查看:82
本文介绍了循环遍历空迭代器不会引发异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是Python 3.6.7.

I am on Python 3.6.7.

我刚刚注意到,在空列表上的for循环甚至不会循环一次. 经过一番思考,这对我来说很有意义. IE.大小为零(空)的对象上的循环返回零次迭代.

I just noticed that a for loop over an empty list does not loop even once. After some thought, that made some sense to me. I.e. a loop over a zero-sized (empty) object returns zero iterations.

iterable = []
for element in iterable:
    pass
print(element)
>>> NameError: name 'element' is not defined

这意味着如果len(iterable) == 0,则不会在循环内执行测试.

This means that a test inside the loop will not be executed if len(iterable) == 0.

iterable = []
for element in iterable:
    assert isinstance(element, int)
#nothing happens

那我该如何捕捉到这种情况?

Then how can I catch this situation?

当由于iterable为空而导致我的循环不运行时,是否存在一种紧凑的内置方法来引发错误?

Is there a compact built-in way to raise an error when my loop does not run because the iterable is empty?

要适应这种特殊情况,需要手动进行:

Catching this particular situation requires manually:

  • 在循环之前测试iterator是否为非空
  • 在循环后测试元素是否已定义.两者都不 方法对我来说似乎很优雅
  • testing that the iterator is non-empty before the loop
  • testing that the element was defined, after the loop. Neither method seems elegant to me

我可能最终在每个for循环中都要进行此测试.

And I may end up having this test in every single for loop.

assert len(iterable) > 0
#loop

#loop
assert "element" in dir() #?

推荐答案

您可以使用

循环语句可以具有else子句;当循环通过穷尽迭代器终止时执行.

Loop statements may have an else clause; it is executed when the loop terminates through exhaustion of the iterable.

例如:

iterator = []
for element in iterator:
    print('This wont print..')
else:
    assert iterator

这将导致:

Traceback (most recent call last):
  File "<pyshell#2>", line 4, in <module>
    assert iterator
AssertionError

这篇关于循环遍历空迭代器不会引发异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆