本文介紹了在 Python 中遍歷列表時刪除元素的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
在 Java 中,我可以使用 Iterator
然后使用 .remove()
迭代器的方法來移除迭代器返回的最后一個元素,像這樣:
In Java I can do by using an Iterator
and then using the .remove()
method of the iterator to remove the last element returned by the iterator, like this:
import java.util.*;
public class ConcurrentMod {
public static void main(String[] args) {
List<String> colors = new ArrayList<String>(Arrays.asList("red", "green", "blue", "purple"));
for (Iterator<String> it = colors.iterator(); it.hasNext(); ) {
String color = it.next();
System.out.println(color);
if (color.equals("green"))
it.remove();
}
System.out.println("At the end, colors = " + colors);
}
}
/* Outputs:
red
green
blue
purple
At the end, colors = [red, blue, purple]
*/
我將如何在 Python 中執行此操作?在 for 循環中迭代列表時,我無法修改列表,因為它會導致內容被跳過(請參閱 這里).而且似乎沒有與 Java 的 Iterator
接口等效的東西.
How would I do this in Python? I can't modify the list while I iterate over it in a for loop because it causes stuff to be skipped (see here). And there doesn't seem to be an equivalent of the Iterator
interface of Java.
推薦答案
遍歷列表的副本:
for c in colors[:]:
if c == 'green':
colors.remove(c)
這篇關于在 Python 中遍歷列表時刪除元素的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!