Valentin Baraneckiy
Valentin Baraneckiy

Reputation: 3

How to delete values from array by using mask?

Subj. For example:

array = ['value1', 'value2', 'value3', 'value4', ...(here is many values like value5, value6, value7, value49 etc.)..., 'value50' 'something', 'something2']

I should delete value* from this array. How can I do this?

Upvotes: 0

Views: 82

Answers (2)

hemraj
hemraj

Reputation: 1034

making simple things complex here is my code :)

from itertools import ifilterfalse
ifilterfalse(lambda x:x.startswith('value'),array)

note if there are integer values in list you will get AttributeError: 'int' object has no attribute 'startswith'

so to handle integer also in your list 'array' we will use this simple loop:

res = []
for ele in array:
if type(ele) is int:
    res.append(ele)
elif not ele.startswith('value'):
    res.append(ele)

Upvotes: 0

falsetru
falsetru

Reputation: 369134

Using list comprehension, filter out values starts with value:

>>> array = ['value1', 'value2', 'value3', 'value4', 'value50', 'something', 'something2']
>>> array = [x for x in array if not x.startswith('value')]  # NOTE: used `not`
>>> array
['something', 'something2']

Upvotes: 3

Related Questions