5

Python 删除列表中的元素

 3 years ago
source link: https://www.lfhacks.com/tech/python-remove-all-occurrence
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Python 删除列表中的元素

965.jpg

首先,列表的 remove() 方法只能删除第一次出现的位置(first occurrence)

>>> x = [1, 2, 1, 2, 1, 2]
>>> x.remove(2)
>>> x
[1, 1, 2, 1, 2]
>>> 

如果要全部删除list里面的某个元素,可以用列表解析方法(List comprehension):

>>> x = [1, 2, 1, 2, 1, 2]
>>> y = [i for i in x if i != 2] #删除全部2
>>> y
[1, 1, 1]
>>>

同样方法可以用来一次性删除多种元素:

>>> x = [1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3]
>>> y = [i for i in x if i != 2 and i != 3] #删除全部2和3
>>> y
[1, 1, 1, 1]
>>> 

删除一个范围:

>>> x = [1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3]
>>> y = [i for i in x if i < 2] #只保留小于2的
>>> y
[1, 1, 1, 1]
>>> 

甚至删除一个集合里的元素:

>>> x = [1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3]
>>> d = [2, 3]
>>> y = [i for i in x if i not in d] #不保留d中的元素 
>>> y
[1, 1, 1, 1]
>>>

坚持原创不易。如果您觉得有收获,请考虑资助本站,以期待更多原创文章。

打赏作者,支持小站

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK