从列表中删除相同的项目

时间:2016-09-05 15:31:25

标签: 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"]

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

2 个答案:

答案 0 :(得分:9)

您可以使用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()返回迭代器,因此,调用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()被使用了。

答案 1 :(得分:1)

使用filter()

lst = ["192.168.1.1", "0.1.2.3", "0.2.3.4", "192.168.1.2", "0.3.4.5, 192.168.1.3"]
new_lst = list(filter(lambda x: x if not x.startswith("0") else None, lst))
print(new_lst)