如何打破for循环? [英] how to break a for loop?
本文介绍了如何打破for循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
你好!
现在是圣彼得堡的1:56点,我还在编码...也许
'这就是我遇到愚蠢问题的原因:我需要从列表开头的
中删除零,但我不能:-(。我用
for i,coef in enumerate(coefs):
if coef == 0:
del coefs [i]
else:
打破
但它会从列表中删除所有零。这是什么?
PS我觉得这个问题很愚蠢。 .. ;-)
Hello!
It''s 1:56 o''clock in St.-Petersburg now, and I am still coding... maybe
that''s why I encountered stupid problem: I need to remove zeros from
the begining of list, but I can''t :-(. I use
for i,coef in enumerate(coefs):
if coef == 0:
del coefs[i]
else:
break
but it removes ALL zeros from list. What''s up?
P.S. I feel SO stupid asking this quastion... ;-)
推荐答案
Gregory Petrosyan写道:
Gregory Petrosyan wrote:
你好!
它'现在是在圣彼得堡的1:56点,我还在编码...也许
这就是为什么我遇到了愚蠢的问题:我需要从
删除零列表的开头,但我不能:-(。我使用
for i,coef in enumerate(coefs):
if coef == 0:
del coefs [i]
否则:
打破
但它会从列表中删除所有零。这是怎么回事?
我不知道枚举是如何实现的,但是我会怀疑在b循环中修改列表对象
到del要求麻烦
尝试
for i,coef in enumerate(coefs [:]):
代替
PS我觉得愚蠢地问这个问题......; - )
Hello!
It''s 1:56 o''clock in St.-Petersburg now, and I am still coding... maybe
that''s why I encountered stupid problem: I need to remove zeros from
the begining of list, but I can''t :-(. I use
for i,coef in enumerate(coefs):
if coef == 0:
del coefs[i]
else:
break
but it removes ALL zeros from list. What''s up?
I don''t know how enumerate is implemented, but I would
suspect that modifying the list object in the loop
through del is asking for trouble
try
for i,coef in enumerate(coefs[:]):
instead
P.S. I feel SO stupid asking this quastion... ;-)
uda4i
hth,Daniel
uda4i
hth, Daniel
zero_list = [0,0,0,0,0,1,2,3,4]
范围内的x(len( zero_list)):
if zero_list [x]!= 0:break
nonzero_list = zero_list [x:]
print nonzero_list
但更多的是pythonic解决方案将从其他用户发布我
猜测:)
HTH
Petr Jakes
zero_list=[0,0,0,0,0,1,2,3,4]
for x in range(len(zero_list)):
if zero_list[x]!=0: break
nonzero_list=zero_list[x:]
print nonzero_list
but some more "pythonic" solutions will be posted from other users I
guess :)
HTH
Petr Jakes
我只花了几秒钟思考它:)
lst = [0,0,0,1,2,3,0 ,11]
尝试:
del lst [0:lst.index(0)]
除了ValueError:
通过
是更好的解决方案
I just spend some more seconds thinking about it :)
lst = [0,0,0,1,2,3,0,11]
try:
del lst[0:lst.index(0)]
except ValueError:
pass
is better solution
这篇关于如何打破for循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文