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

MRAB python at mrabarnett.plus.com
Fri Nov 6 18:33:54 CET 2009


Peng Yu wrote:
> On Fri, Nov 6, 2009 at 10:42 AM, Robert P. J. Day <rpjday at crashcourse.ca> wrote:
>> On Fri, 6 Nov 2009, Peng Yu wrote:
>>
>>> On Fri, Nov 6, 2009 at 3:05 AM, Diez B. Roggisch <deets at nospam.web.de> wrote:
>>>> Peng Yu schrieb:
>>>>> 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.
>>>> Nonsense. For processing over each element, you have to loop over them,
>>>> either with or without growing a call-stack at the same time.
>>>>
>>>> FP languages can optimize away the stack-frame-growth (tail recursion) - but
>>>> this isn't reducing complexity in any way.
>>>>
>>>> So use a loop, either directly, or using a list-comprehension.
>>> What is a list-comprehension?
>>>
>>> I tried the following code. The list 'l' will be ['a','b','c'] rather
>>> than ['b','c'], which is what I want. It seems 'remove' will disrupt
>>> the iterator, right? I am wondering how to make the code correct.
>>>
>>> l = ['a', 'a', 'b', 'c']
>>> for x in l:
>>>   if x == 'a':
>>>     l.remove(x)
>>>
>>> print l
>>  list comprehension seems to be what you want:
>>
>>  l = [i for i in l if i != 'a']
> 
> My problem comes from the context of using os.walk(). Please see the
> description of the following webpage. Somehow I have to modify the
> list inplace. I have already tried 'dirs = [i for i in l if dirs !=
> 'a']'. But it seems that it doesn't "prune the search". So I need the
> inplace modification of list.
> 
[snip]
You can replace the contents of a list like this:

     l[:] = [i for i in l if i != 'a']




More information about the Python-list mailing list