一个关于 for 和 while 语句的问题

2019-11-05 21:56:26 +08:00
 fengyi0524
sandwich_orders = ["pastrami","vegetable","chicken","pastrami","pastrami"]
finished_sandwiches = []
#while sandwich_orders:
for sandwich_order in sandwich_orders:
print("I made your " + sandwich_order + " sandwich")
sandwich_orders.remove(sandwich_order)

输出是:

I made your pastrami sandwich
I made your chicken sandwich
I made your pastrami sandwich

如果不注释掉 while 语句,就可以全部输出:

I made your pastrami sandwich
I made your chicken sandwich
I made your pastrami sandwich
I made your vegetable sandwich
I made your pastrami sandwich

请问为什么只用 for 语句会出现输出不完整的情况?添加了 while 语句后为什么可以避免出现问题?
2155 次点击
所在节点    Python
4 条回复
ZeldaPeach
2019-11-05 23:33:01 +08:00
list 的 for ... in 迭代,是内部生成一个计数器,从 0 开始,每次加 1,将这个数字作为索引取该 list 的元素,直到产生 StopIteration 终止
内部计数器从 0 开始
list 为 ["pastrami","vegetable","chicken","pastrami","pastrami"]
给出 list[0] 用作迭代,此时为 "pastrami"
删掉"pastrami",list 变为 ["vegetable","chicken","pastrami","pastrami"]
内部计数器加 1 变为 1
给出 list[1] 用作迭代,此时为 "chicken",那个 "vegetable" 的索引已经变为 0 了,所以被跳过了
删掉 "chicken",list 变为 ["vegetable","pastrami","pastrami"]
内部计数器加 1 变为 2
给出 list[2] 用作迭代,此时为 "pastrami"
删掉 "pastrami",list 变为 ["vegetable","pastrami"]
内部计数器加 1 变为 3
给出 list[3] 用作迭代,超过现在 list 的长度,触发 StopIteration,迭代终止

此时如果 while list,因为非空,所以再将 ["vegetable","pastrami"] 进行 for 迭代
list[0] -> "vegetable",删掉此元素,list 变为 ["pastrami"]
list[1] -> StopIteration,迭代终止

再 while list,还有一个元素,所以再将 ["pastrami"] 进行 for 迭代
list[0] -> "pastrami",删掉此元素,list 变为 []
list[1] -> StopIteration,迭代终止

再 while list,空列表,不再继续,while 结束
ZeldaPeach
2019-11-05 23:39:49 +08:00
官方文档
docs.python.org/3/reference/compound_stmts.html#the-for-statement
这一小节最后的 note 把这个使用 internal counter 的迭代机制讲了
XIVN1987
2019-11-06 09:13:14 +08:00
不能在遍历 sandwich_orders 的同时对 sandwich_orders 进行增减 item 吧
eggs
2019-11-10 19:30:17 +08:00
不行

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/616647

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX