You can use a list comprehension to create a new list containing only the elements you don't want to remove:
(您可以使用列表推导来创建一个仅包含您不想删除的元素的新列表:)
somelist = [x for x in somelist if not determine(x)]
Or, by assigning to the slice somelist[:]
, you can mutate the existing list to contain only the items you want:
(或者,通过将切片分配给somelist[:]
,您可以将现有列表突变为仅包含所需的项目:)
somelist[:] = [x for x in somelist if not determine(x)]
This approach could be useful if there are other references to somelist
that need to reflect the changes.
(如果还有其他引用要反映更改的somelist
,则此方法可能很有用。)
Instead of a comprehension, you could also use itertools
.
(除了理解之外,您还可以使用itertools
。)
In Python 2: (在Python 2中:)
from itertools import ifilterfalse
somelist[:] = ifilterfalse(determine, somelist)
Or in Python 3:
(或在Python 3中:)
from itertools import filterfalse
somelist[:] = filterfalse(determine, somelist)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…