问题:
请推测一下, 下面的程序输出结果是什么?
- def test_iterator2():
- nums = [1, 2, 3, 4]
- for i in nums:
- nums.remove(i)
- print(nums)
好, 我们看一下这段程序的实际执行结果是什么, 跟我们的推断是否一致 :
[2, 4]
为什么会是这个结果呢? 我们首选需要了解 Python 的一个循环机制: Python 中的 for 循环实质是一个迭代器 iterator, 它不断调用 next 方法返回下一个值, 比如:
- for x in nums:
- print(x)
等价于:
- it = iter(nums)
- while True:
- try:
- print(*it)
- x = next(it)
- except StopIteration:
- break
而 list 中的 remover 方法是遍历 list 中的元素, 删除对应的值.
题目中 remover 之后又调用了一次 next 方法, 出现了 [2,4] 的结果 ܺ+
来源: https://www.qcloud.com/developer/article/1338261