简体   繁体   English

如何在某个索引处中断while循环,然后运行到列表末尾?

[英]How to break while loop at a certain index but then run until end of a list?

I have the code below, I wish to run the while loop to remove a specific value from the list but not remove it on a certain index and still loop through the whole list without removing that specific occurrence.我有下面的代码,我希望运行 while 循环以从列表中删除特定值,但不在某个索引上删除它,并且仍然循环整个列表而不删除该特定事件。

a = 20
i = [5, 15, 20, 25, 50, 20, 80, 90, 20]
while a in i:
   i.remove(a)
    if a == i.index(5):
       continue
  print(i)

Maybe it's not supposed to be done with while loop but since learning the break or continue functions, i thought to give it a try.也许它不应该用 while 循环来完成,但自从学习了 break 或 continue 函数后,我想试一试。 Thanks!谢谢!

Typically something you can solve with a list comprehension:通常,您可以通过列表理解来解决一些问题:

[ el for i, el in enumerate(lst) if i == 3 or el != 25]

Creates a new list while looping over the original one and adds all the elements that are not 25 (the one you want to remove) but still adds it if i==3, the position that is protected.在循环原始列表时创建一个新列表,并添加所有不是 25 的元素(您要删除的那个),但如果 i==3 仍会添加它,即受保护的 position。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM