首页 > 文章列表 > python迭代中删除列表项目

python迭代中删除列表项目

python迭代
223 2022-08-07

1、可以使用列表理解来创建仅包含不想删除的元素的新列表。

somelist = [x for x in somelist if not determine(x)]

2、通过分配给slice somelist[:],改变现有列表以仅包含想要的项目。

somelist[:] = [x for x in somelist if not determine(x)]

3、如果有其他somelist需要反映更改的参考,则此方法可能很有用。

除了理解,还可以使用itertools. 在Python2中:

from itertools import ifilterfalse
somelist[:] = ifilterfalse(determine, somelist)

或者在Python3中:

from itertools import filterfalse
somelist[:] = filterfalse(determine, somelist)

本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。