allexj allexj - 3 months ago 8
Python Question

Delete similar items that start the same from a list

For example, I have this list:

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"]


How can I remove with a command all the items that start with
"0."
?

Answer

You can filter the desired items in a list using a list comprehension using str.startswith() to check if a string starts with "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']

Note that list is not a good variable name - it shadows the built-in list.


You can also approach the problem with filter() and a filtering function:

>>> 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']

Note that in Python 3.x, unlike Python 2.x, filter() returns an iterator, hence, calling list() to demonstrate the result.


And, a "just for fun" option and to demonstrate how can you overcomplicate the problem with different functional programming-style tools:

>>> 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() and operator.methodcaller() were used.