diegus diegus - 5 months ago 10
Python Question

python: filter a list of strings based on a string name

I have a lists of strings that look like this:

li1 = ['pin 2.3','vlo 5.4', 'lu 1.3', '3 packages installed', '', 'bla']

l12 = ['pin 2.3','vlo 5.4', '2 packages installed', 'bla', 'bla']


I want to filter out from the lists the strings 'x packages installed' and those that follow to have:

out1 = ['pin 2.3','vlo 5.4', 'lu 1.3']


out2 = ['pin 2.3','vlo 5.4']


How can I do that using list comprehension? thanks

Answer

You can use itertools.takewhile, which takes items from the list until the given condition is not passed:

from itertools import takewhile

l12 = ['pin 2.3','vlo 5.4', '2 packages installed', 'bla', 'bla']
li1 = ['pin 2.3','vlo 5.4', 'lu 1.3', '3 packages installed', '', 'bla']



r12 = takewhile(lambda x: "packages installed" not in x, l12)
ri1 = takewhile(lambda x: "packages installed" not in x, li1)
print(list(r12))
# ['pin 2.3', 'vlo 5.4']

print(list(ri1))
# ['pin 2.3', 'vlo 5.4', 'lu 1.3']