python - 为什么这里没有引发 StopIteration ?

标签 python iterator

看看这个,问题的关键在底部:

>>> scan = iter('FHUR203459')
>>> while True:
        print(next(scan))


F
H
U
R
2
0
3
4
5
9
Traceback (most recent call last):
  File "<pyshell#11>", line 2, in <module>
    print(next(scan))
StopIteration
>>> scan = iter('FHUR203459')
>>> for i in range(12):  # 12 * 2 for each join is 24, much longer than the string; should raise error.
        print(''.join(next(scan) for i in range(2)))


FH
UR
20
34
59







>>>

换句话说,我们可以看到迭代器在两种情况下都到达了末尾,但是它只在第一种情况下引发了 StopIteration,即使 next() 是到达终点后在这两种情况下都使用。为什么在 join 中使用它似乎可以避免该错误?或者这是一个错误?

最佳答案

在第一种情况下,StopIteration没有在任何地方处理。但在第二种情况下,

''.join(next(scan) for i in range(2))

我们将生成器表达式传递给''.join ,它处理 StopIterationnext(scan) 提出并且每次都会退出。这就是为什么''.join产生空字符串。

您可以稍微修改一下,并将列表传递给 ''.join并查看自己引发的异常,如下所示

>>> scan = iter('FHUR203459')
>>> for i in range(12):
...     print(''.join([next(scan) for i in range(2)]))
... 
FH
UR
20
34
59
Traceback (most recent call last):
  File "<input>", line 2, in <module>
  File "<input>", line 2, in <listcomp>
StopIteration

它表明StopIteration实际上,这一次,列表理解受到了影响。

关于python - 为什么这里没有引发 StopIteration ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26552333/

相关文章:

python - 使用 pyinstaller 后,我的程序在运行 subprocess.run() 命令时卡住

python - 找到具有 k 个唯一字母的最大可能子串。 (递归)

python - 按最后日期的唯一名称和状态分组

python - 从 2.3.1 升级到 Spark2.4.2 但 mongodb 连接器停止工作

c++ - 如何返回通用迭代器(独立于特定容器)?

java - 迭代器:Java 中最后一个元素的迭代器

c++ - 模板类之间的可见性

Python ctypes : How to call a function which should return an array of strings?

rust - 如何在 Rust 中使用 BigInt 和 Bigint 生成一系列值?

python - 如何在python中的while循环语句中使用迭代器