久久久久久久av_日韩在线中文_看一级毛片视频_日本精品二区_成人深夜福利视频_武道仙尊动漫在线观看

在 Python 中遍歷列表時刪除元素

Remove elements as you traverse a list in Python(在 Python 中遍歷列表時刪除元素)
本文介紹了在 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模板網!

【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!

相關文檔推薦

How to draw a rectangle around a region of interest in python(如何在python中的感興趣區域周圍繪制一個矩形)
How can I detect and track people using OpenCV?(如何使用 OpenCV 檢測和跟蹤人員?)
How to apply threshold within multiple rectangular bounding boxes in an image?(如何在圖像的多個矩形邊界框中應用閾值?)
How can I download a specific part of Coco Dataset?(如何下載 Coco Dataset 的特定部分?)
Detect image orientation angle based on text direction(根據文本方向檢測圖像方向角度)
Detect centre and angle of rectangles in an image using Opencv(使用 Opencv 檢測圖像中矩形的中心和角度)
主站蜘蛛池模板: 成人深夜福利网站 | 一级片视频免费观看 | 日本不卡一区 | 欧美精品1区 | 日韩另类视频 | 一区二区三区四区国产 | 精品一区二区三区四区五区 | 亚洲一区二区中文字幕在线观看 | 一区中文字幕 | 成年免费大片黄在线观看岛国 | 久久精品国内 | 国产成人高清视频 | 亚洲第一中文字幕 | 国产在线91| 国产精品av久久久久久毛片 | 欧美高清视频一区 | 精品国产乱码久久久久久牛牛 | 春色av| 超碰国产在线 | 久久久久久一区 | 激情视频网站 | 国产aⅴ | 久久久99精品免费观看 | 在线观看成年视频 | 国产精品激情小视频 | 久久久国产亚洲精品 | 久久国产麻豆 | 91大神xh98xh系列全部 | 久久99精品国产自在现线小黄鸭 | 黄色一级大片视频 | 日韩欧美中文字幕在线观看 | 久久lu | 成人网在线观看 | 一区二区三区四区av | av性色全交蜜桃成熟时 | 国产精品区二区三区日本 | 亚洲激情av | 一区二区三区免费 | 国产精品一区在线 | 国产久| 狠狠插天天干 |