On 03/12/15 02:15, c.bu...@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.

btw: Is it correct to iterate over a copy (list[:]) of that string list
and not the original one?


No idea how 'Pythonic' this would be considered, but you could use a combination of filter() with a regular expression :

# ------------------------------------------------------------------
import re

list = ...

pattern = re.compile( r'banana|car', re.I )
filtered_list = filter( lambda line: not pattern.search(line), list )
# ------------------------------------------------------------------

HTH

--
https://mail.python.org/mailman/listinfo/python-list

Reply via email to