What is the best way to delete strings in a string list that that match certain pattern?

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Fri Nov 6 01:59:39 EST 2009


En Fri, 06 Nov 2009 02:23:12 -0300, Peng Yu <pengyu.ut at gmail.com> escribió:
> On Thu, Nov 5, 2009 at 10:25 PM, Chris Rebert <clp2 at rebertia.com> wrote:
>> On Thu, Nov 5, 2009 at 8:19 PM, Peng Yu <pengyu.ut at gmail.com> wrote:

>>> Suppose I have a list of strings, A. I want to compute the list (call
>>> it B) of strings that are elements of A but doesn't match a regex. I
>>> could use a for loop to do so. In a functional language, there is way
>>> to do so without using the for loop.
>>>
>>> I'm wondering what is the best way to compute B in python.
>>
>> Since this sounds rather homework-y, I'll only give you a pointer:
>> http://docs.python.org/tutorial/datastructures.html#list-comprehensions
>
> Now, I want to in-place delete elements in A that matches the regex. I
> know that I need to use del. But I'm not sure how to use the
> functional style programming for this problem. Would you please let me
> know?

Functional and del don't mix. What about:

B = [item for item in A if regex.match(item) is None]
B = filter(lambda item: regex.match(item) is None, A)

-- 
Gabriel Genellina




More information about the Python-list mailing list