Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #99968 > unrolled thread

Re: filter a list of strings

Started byTerry Reedy <tjreedy@udel.edu>
First post2015-12-03 11:19 -0500
Last post2015-12-03 11:19 -0500
Articles 1 — 1 participant

Back to article view | Back to comp.lang.python

This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by below is the oldest one visible, not the original post.


Contents

  Re: filter a list of strings Terry Reedy <tjreedy@udel.edu> - 2015-12-03 11:19 -0500

#99968 — Re: filter a list of strings

FromTerry Reedy <tjreedy@udel.edu>
Date2015-12-03 11:19 -0500
SubjectRe: filter a list of strings
Message-ID<mailman.176.1449159615.14615.python-list@python.org>
On 12/3/2015 7:28 AM, Mark Lawrence wrote:
> On 03/12/2015 01:15, c.buhtz@posteo.jp wrote:
>> I would like to know how this could be done more elegant/pythonic.
>>
>> I have a big list (over 10.000 items) with strings (each 100 to 300
>> chars long) and want to filter them.
>>
>> list = .....
>>
>> for item in list[:]:
>>    if 'Banana' in item:
>>       list.remove(item)
>>    if 'Car' in item:
>>       list.remove(item)
>>
>> There are a lot of more conditions of course. This is just example code.
>> It doesn't look nice to me. To much redundance.
>
> targets = ['Banana', 'Car'...]
> for item in list[:]:
>      for target in targets:
>          if target in item:
>              list.remove(item)
>
>>
>> btw: Is it correct to iterate over a copy (list[:]) of that string list
>> and not the original one?
>>
>
> Absolutely :)

Even better, instead of copying and deleting, which is O(k*n), where n 
is the len of list and k is number deletions, is to create a new list 
with the item you want.  In other words, actually filter, as you said 
you want.

targets = {'Banana', 'Car', ...}  # set intentional
newlist = [item for item in oldlist if item not in targets]

Generically, replace 'not in targets' with any boolean expression or 
function.


-- 
Terry Jan Reedy

[toc] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web