Python:在迭代列表時刪除列表元素[重複] - Python: Removing list element while iterating over list [duplicate]

問題:

This question already has answers here : 這個問題在這裏已經有了答案
Closed 6 years ago . 6年前關閉。

I'm iterating over a list of elements in Python, do some action on it, and then remove them if they meet certain criteria.我正在迭代 Python 中的元素列表,對其執行一些操作,然後在滿足某些條件時將其刪除。

for element in somelist:
    do_action(element)
    if check(element):
        remove_element_from_list

What should I use in place of remove_element?我應該用什麼來代替 remove_element? I have seen similar questions asked, but notice the presence of the do_action part that is to be executed for all elements and thus eliminates the solution of using filters.我看到過類似的問題,但請注意要爲所有元素執行的 do_action 部分的存在,因此消除了使用過濾器的解決方案。


解決方案:

參考: https://stackoom.com/en/question/PGnM
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章