allexj allexj - 1 year ago 132
Python Question

Delete similar items that start the same from a list

For example, I have this list:

list = ["", "", "", "", "", ""]

How can I remove with a command all the items that start with

Answer Source

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 = ['', '', '', '', '', '']
>>> [item for item in l if not item.startswith('0.')]
['', '', '', '']

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))
['', '', '', '']

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))
['', '', '', '']

itertools.filterfalse() and operator.methodcaller() were used.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download