遍历列表的不同方法 [英] Different ways of Iterating over a list

查看:69
本文介绍了遍历列表的不同方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以告诉我这段代码有什么区别吗?

Can somebody tell me what's the difference between this code:

x = [1, 2, 3, 4, 5, 6, 7]
for i in x[:]:
    if i == 5:
        x.insert(0, i)

这段代码:

x = [1, 2, 3, 4, 5, 6, 7]
for i in x:
    if i == 5:
        x.insert(0, i)

第二个为什么不起作用?我知道Python教程中已经提到了它,但是我不太明白.

Why doesn't the second one work? I know it is mentioned in the Python tutorial, but I can't quite understand it.

推荐答案

在第一个版本中,您将创建一个副本(通过从头到尾对列表进行切片),而在第二个版本中,您将遍历原始版本列表.

In the first version, you create a copy (by slicing the list from the beginning to the end), in the second one you're iterating over the original list.

如果您要遍历一个容器,则其大小在迭代期间不会更改,这是有充分原因的(请参见下文).但是,由于调用了x.insert,因此列表的大小发生了变化.

If you iterate over a container, its size can't change during iteration, for good reasons (see below). But since you call x.insert, the size of your list changes.

如果执行第二个版本,它实际上并不会立即引发错误,而是会无限期地继续运行,并用越来越多的5s填充列表:

If you execute the second version, it actually doesn't throw an error immediately, but continues indefinitely, filling the list up with more and more 5s:

一旦您位于列表索引4(因此i为5),您将在列表的开头插入5:

Once you're at the list index 4 (and i is therefore 5), you're inserting a 5 at the beginning of the list:

[5, 1, 2, 3, 4, 5, 6, 7]

然后您继续循环,将索引隐式地增加到5,现在又是5,因为由于插入,整个列表向右移了一个,所以将再次插入5:

You then continue in the loop, implicitly increasing your index to 5, which is now again 5, because the whole list got shifted one to the right, due to your insertion, so 5 will be inserted again:

[5, 5, 1, 2, 3, 4, 5, 6, 7]

这种情况永远持续下去(直到出现MemoryError).

This goes on "forever" (until there's a MemoryError).

这篇关于遍历列表的不同方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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