Skip to main content
 首页 » 编程设计

python之从列表中删除开头相同的相似项目

2025年05月04日10pengyingh

例如,我有这个列表:

list = ["192.168.1.1", "0.1.2.3", "0.2.3.4", "192.168.1.2", "0.3.4.5", "192.168.1.3"] 

如何使用命令删除所有以 "0." 开头的项目?

请您参考如下方法:

您可以使用 list comprehension 过滤列表中所需的项目使用 str.startswith()检查字符串是否以“0”开头。

>>> l = ['192.168.1.1', '0.1.2.3', '1.2.3.4', '192.168.1.2', '0.3.4.5', '192.168.1.3'] 
>>> [item for item in l if not item.startswith('0.')] 
['192.168.1.1', '1.2.3.4', '192.168.1.2', '192.168.1.3'] 

请注意 list 不是一个好的变量名 - 它 shadows内置的 list。


您也可以使用 filter() 解决问题和过滤功能:

>>> list(filter(lambda x: not x.startswith("0."), l)) 
['192.168.1.1', '1.2.3.4', '192.168.1.2', '192.168.1.3'] 

请注意,在 Python 3.x 中,与 Python 2.x 不同,filter() 返回一个 iterator,因此调用 list() 展示结果。


还有一个“只是为了好玩”的选项,并演示如何使用不同的函数式编程风格的工具将问题复杂化:

>>> from operator import methodcaller 
>>> from itertools import filterfalse 
>>> 
>>> list(filterfalse(methodcaller('startswith', "0."), l)) 
['192.168.1.1', '1.2.3.4', '192.168.1.2', '192.168.1.3'] 

itertools.filterfalse()和 operator.methodcaller()被使用了。