从列表中删除相同的项目

Spe*_*987 1 python list python-3.x

例如,我有这个列表:

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"]
Run Code Online (Sandbox Code Playgroud)

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

ale*_*cxe 9

您可以使用过滤器在列表中选择所需的项目列表解析使用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']
Run Code Online (Sandbox Code Playgroud)

请注意,这list不是一个好的变量名称 - 它会影响内置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']
Run Code Online (Sandbox Code Playgroud)

请注意,在Python 3.x中,与Python 2.x不同,filter()返回迭代器,因此,调用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']
Run Code Online (Sandbox Code Playgroud)

itertools.filterfalse()operator.methodcaller()使用.