至于 for 循环中实际发生了什么:
来自Python for statement documentation:
表达式列表被评估一次;它应该产生一个可迭代的
目的。为expression_list 的结果创建一个迭代器。
然后,该套件对由
迭代器,按索引升序。每个项目依次是
使用标准分配规则分配给目标list,
然后执行套件。 物品用完时(即
当序列为empty时立即),else 子句中的套件,
如果存在,则执行,loop 终止。
我认为最好借助插图来展示它。
现在,假设您有一个像这样的iterable object(例如list):
out = [a, b, c, d, e, f]
当您执行for x in out 时会发生什么,它创建内部索引器,如下所示(我用符号^ 说明它):
[a, b, c, d, e, f]
^ <-- here is the indexer
通常发生的情况是:当您完成循环的一个循环时,索引器会向前移动,如下所示:
[a, b, c, d, e, f] #cycle 1
^ <-- here is the indexer
[a, b, c, d, e, f] #cycle 2
^ <-- here is the indexer
[a, b, c, d, e, f] #cycle 3
^ <-- here is the indexer
[a, b, c, d, e, f] #cycle 4
^ <-- here is the indexer
[a, b, c, d, e, f] #cycle 5
^ <-- here is the indexer
[a, b, c, d, e, f] #cycle 6
^ <-- here is the indexer
#finish, no element is found anymore!
如您所见,索引器会一直向前移动,直到结束
列表,不管列表发生了什么!
因此,当您执行remove 时,这就是内部发生的情况:
[a, b, c, d, e, f] #cycle 1
^ <-- here is the indexer
[b, c, d, e, f] #cycle 1 - a is removed!
^ <-- here is the indexer
[b, c, d, e, f] #cycle 2
^ <-- here is the indexer
[c, d, e, f] #cycle 2 - c is removed
^ <-- here is the indexer
[c, d, e, f] #cycle 3
^ <-- here is the indexer
[c, d, f] #cycle 3 - e is removed
^ <-- here is the indexer
#the for loop ends
请注意,那里只有 3 个循环,而不是 6 个循环(!!)(这是原始列表中的元素数)。这就是为什么您留下了原来len 的一半 len,因为这是在每个循环中从循环中删除一个元素时完成循环所需的循环数。 p>
如果您想清除列表,只需执行以下操作:
if (out != []):
out.clear()
或者,或者,要逐个删除元素,您需要反过来 - 从结尾到开头。使用reversed:
for x in reversed(out):
out.remove(x)
现在,reversed 为什么会起作用?如果索引器继续前进,reversed 是否也不应该工作,因为每个周期的元素数量都会减少一个?
不,不是这样的,
因为reversed方法改变了内部索引器的方式
作品!当您使用 reversed 方法时发生的事情是
内部索引器向后移动(从末尾)而不是
前进。
为了说明,这是通常发生的情况:
[a, b, c, d, e, f] #cycle 1
^ <-- here is the indexer
[a, b, c, d, e, f] #cycle 2
^ <-- here is the indexer
[a, b, c, d, e, f] #cycle 3
^ <-- here is the indexer
[a, b, c, d, e, f] #cycle 4
^ <-- here is the indexer
[a, b, c, d, e, f] #cycle 5
^ <-- here is the indexer
[a, b, c, d, e, f] #cycle 6
^ <-- here is the indexer
#finish, no element is found anymore!
因此,当您每个周期执行一次删除时,它不会影响索引器的工作方式:
[a, b, c, d, e, f] #cycle 1
^ <-- here is the indexer
[a, b, c, d, e] #cycle 1 - f is removed
^ <-- here is the indexer
[a, b, c, d, e] #cycle 2
^ <-- here is the indexer
[a, b, c, d] #cycle 2 - e is removed
^ <-- here is the indexer
[a, b, c, d] #cycle 3
^ <-- here is the indexer
[a, b, c] #cycle 3 - d is removed
^ <-- here is the indexer
[a, b, c] #cycle 4
^ <-- here is the indexer
[a, b] #cycle 4 - c is removed
^ <-- here is the indexer
[a, b] #cycle 5
^ <-- here is the indexer
[a] #cycle 5 - b is removed
^ <-- here is the indexer
[a] #cycle 6
^ <-- here is the indexer
[] #cycle 6 - a is removed
^ <-- here is the indexer
希望插图可以帮助您了解内部发生的情况......