为了账号安全,请及时绑定邮箱和手机立即绑定

python for 循环列表并且pop,为什么不走完?

python for 循环列表并且pop,为什么不走完?

蝴蝶刀刀 2019-10-16 09:51:42
for循环一个列表,每次pop都会删除最后一个值,形成新的列表,但是pop删了几次就失效了。a=['a','b','c','d',1,2,3,4,5,6]foriina:a.pop()print(a,'--')以下是结果:/usr/local/bin/python3.7/code/pop2.py['a','b','c','d',1,2,3,4,5]--['a','b','c','d',1,2,3,4]--['a','b','c','d',1,2,3]--['a','b','c','d',1,2]--['a','b','c','d',1]--Processfinishedwithexitcode0想问下为什么到['a','b','c','d',1]--就停止了不继续执行pop了。
查看完整描述

2 回答

?
www说

TA贡献1775条经验 获得超8个赞

python3.7theforstatement
Note:Thereisasubtletywhenthesequenceisbeingmodifiedbytheloop(thiscanonlyoccurformutablesequences,e.g.lists).Aninternalcounterisusedtokeeptrackofwhichitemisusednext,andthisisincrementedoneachiteration.Whenthiscounterhasreachedthelengthofthesequencetheloopterminates.......
for...in...内部维护了一个下标,当下标达到list长度之后循环就结束了。
你现在在循环内部删元素,list长度越来越小,当删掉一半的时候,下标就超过list长度了。
                            
查看完整回答
反对 回复 2019-10-16
?
心有法竹

TA贡献1866条经验 获得超5个赞

问题出现在,你在循环内部删除元素,当i为1时,刚好把2删除。此时i已经到a尾部了,所以下次就退出了。如果想遍历完,应该是foriinrange(len(a)):a.pop()
                            
查看完整回答
反对 回复 2019-10-16
  • 2 回答
  • 0 关注
  • 1058 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信