Home > Blockchain >  How to use itertools to remove lines starting with one of a list of strings
How to use itertools to remove lines starting with one of a list of strings

Time:11-05

I assume this is a good task for Python's itertools. But I don't get it which one of it's magic methods I should use here.

The input data

kill = ['err A', 'err B', 'err C'] 
lines = ['keep A', 'err B foo', 'err A bar', 'keep B', 'err C foobar']

The expected output

['keep A', 'keep B']

Very conservatively I would solve it like this

for e in lines:
     ok = True
     for k in kill:
         if e.startswith(k):
             ok = False
     if ok:
         result.append(e)

Can itertools help me here?

CodePudding user response:

There's no need for itertools, just use a list comprehension. You can convert kill to a tuple, and then it can be used as the argument to startswith().

killt = tuple(kill)
result = [line for line in lines if not line.startswith(killt)]

CodePudding user response:

Barmar already took the obvious one, so here are two itertools ones just for fun:

from itertools import compress, repeat
from operator import not_

result = list(compress(lines, map(not_, map(str.startswith, lines, repeat(tuple(kill))))))
from itertools import filterfalse
from operator import methodcaller

result = list(filterfalse(methodcaller('startswith', tuple(kill)), lines))
  • Related