Python for 循环跳过项目 [英] Python for loop skips item

查看:73
本文介绍了Python for 循环跳过项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有这个代码:

animals = ['cat', 'dog', 'waffle', 'giraffe', 'turtle']
breakfeast_foods = ['waffle', 'pancake', 'eggs']
for index, item in enumerate(animals):
    print item
    if item in breakfeast_foods:
        animals.pop(index)

出于某种原因,循环打印语句没有打印giraffe".我不知道为什么,是不是我遗漏了什么?

And for some reason the loop print statement does not print 'giraffe.' I don't know why, is there something I'm missing?

推荐答案

首先,它实际上是早餐而不是早餐.你打破(结束)的是斋戒(不吃东西),而不是盛宴(吃很多食物).

First things first, it's actually breakfast rather than breakfeast. What you're breaking (ending) is the fast (going without food) rather than the feast (having lots of food).

但这只是我迂腐:-)

现在,进入实际问题.您不应该在枚举列表时修改它(从技术上讲,您可以这样做,但您会得到像您所见的奇怪结果).

Now, on to the actual question. You should not modify the list while enumerating it (technically, you are allowed to do this but you will get strange results like you've seen).

这样做会弄乱用于枚举的内部结构.这是一个简化的解释 (a) 但它应该说明这个概念:

Doing so messes up the internal structures used for the enumeration. This is a simplified explanation (a) but it should illustrate the concept:

把枚举想象成只是使用索引遍历animals中的每个元素.

Think of the enumeration as just stepping through each element in animals using the index.

当您到达索引 2(华夫饼)并发现它在 breakfast_foods 中时,您删除该索引处的项目并将其他项目一起移动,以便您现在拥有:

When you get to index 2 (waffle) and you find it's in breakfast_foods, you remove the item at that index and shuffle the other ones along so that you now have:

['cat', 'dog', 'giraffe', 'turtle']

然后枚举移动到索引 3(现在是乌龟),然后将其打印出来,在此过程中跳过长颈鹿.

Then the enumeration moves on to index 3 (which is now turtle) and you print that out, skipping giraffe in the process.

无论如何,也许更 Pythonic 的方法是:

In any case, perhaps a more Pythonic way of doing this would be:

animals = [x for x in animals if x not in breakfast_foods]

<小时>

(a) Python 的特定实现是使用简单数组还是其他数据结构在这里并不重要.解释只是为了说明在迭代数据结构时更改数据结构通常会导致异常.


(a) Whether a particular implementation of Python uses simple arrays or other data structures is not really important here. The explanation is simply to illustrate that changing a data structure while iterating over it can often cause weirdness.

这篇关于Python for 循环跳过项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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