python - for-loop 在 python 中是如何工作的
问题描述
我曾经认为python中的for循环是iter(iterable)
这样工作next(that_new_iterator_object)
的StopIteration
else
>>> a = [1,2,3,4,5,6,7,8,9]
>>> for i in a:
del a[-1]
print(i)
1
2
3
4
5
其他数字在哪里 6,7,8,9 for-loop 创建的新迭代器对象和变量 a 不同
解决方案
for 循环就像你描述的那样工作。但是,列表迭代器的工作原理大致如下:
class ListIterator:
def __init__(self, lst):
self.lst = lst
self.idx = 0
def __iter__(self):
return self
def __next__(self):
if self.idx >= len(self.lst):
raise StopIteration
else:
val = self.lst[self.idx]
self.idx += 1
return val
IOW,迭代器取决于您正在修改的列表。
所以观察:
>>> class ListIterator:
... def __init__(self, lst):
... self.lst = lst
... self.idx = 0
... def __iter__(self):
... return self
... def __next__(self):
... if self.idx >= len(self.lst):
... raise StopIteration
... else:
... val = self.lst[self.idx]
... self.idx += 1
... return val
...
>>> a = list(range(10))
>>> iterator = ListIterator(a)
>>> for x in iterator:
... print(x)
... del a[-1]
...
0
1
2
3
4
>>>
推荐阅读
- c# - 带有 sql 的只读数据网格列
- c - 如何使用带有可变数量参数的标记粘贴运算符?
- python - TypeError:不能在类似字节的对象上使用字符串模式?这个程序会出现以下错误,为什么?
- angular - 仅测试是否调用了 ngrx 操作就足够了吗?(单元测试)
- python - 在 Python 中快速将长音频文件转换为文本
- r - 使用带有参考书目风格的 natbib 的 RStudio 进行引用时出现问题
- php - 交替查询多个 Wordpress 帖子类型
- python - 如何在使用 python 抓取期间有效地解析大型列表数据?
- laravel - 仅在需要时使用 Echo 在 Laravel-Vue js 应用程序中建立与 Pusher 的连接
- c - 当我们将动态数组作为参数传递给函数时,为什么要使用双指针?