首页 > 解决方案 > Python: remove elements of a list satisfying a condition

问题描述

Given a Python list, I'd like to remove "bad" elements. For example, given a list of lists of integers, I'd like to remove lists beginning with a negative integer. Here's an attempt and failure:

S=[[1,1],[2,1],[-1,1],[-2,1]]

for s in S:    
    if s[0]<0:
        S.remove(s)

which returns

[[1, 1], [2, 1], [-2, 1]]

I'd like to know why the above code doesn't work as expected (it would be instructive), as well as the right way to do this. (I know that I can create a new list where I add those lists of S with positive first element, but I'd rather not make a new list unless necessary.)

标签: pythonlist

解决方案


推荐阅读