Lorzen
Lorzen

Reputation: 185

Beautify/shorten concatenated for loops

I am checking a list of strings if they contain specific substrings. Depending on the conditions, the string from the list is added to another list, or is left out respectively.

This is what I have so far. It is working, but there are quite some loops concatenated. Is there a better (or more pythonesque) way of writing this?

varNams = ['fee1.foo.bar','fee1.foo','fee2.foo.bar','fee2.foo']
selection = []

sub_incl = ['foo']
sub_excl = ['bar']

for i in range(len(varNams)):
    for sub_in in sub_incl:
        for sub_ex in sub_excl:
            if sub_in in varNams[i] and sub_ex not in varNams[i]:
                selection.append(varNams[i])

Upvotes: 0

Views: 47

Answers (2)

David Molina
David Molina

Reputation: 161

My solution is using regex

import re

varNams = ['fee1.foo.bar','fee1.foo','fee2.foo.bar','fee2.foo']
selection = []

regex1='foo'
regex2='bar'

for i in varNams:
    if re.search(regex1, i) and not re.search(regex2, i):
        selection.append(i)

Upvotes: 1

python_user
python_user

Reputation: 7113

You can use itertools.product in a list comprehension.

from itertools import product

varNams = ['fee1.foo.bar','fee1.foo','fee2.foo.bar','fee2.foo']

sub_incl = ['foo']
sub_excl = ['bar']

res = [i for i in varNams for sub_in, sub_ex in product(sub_incl, sub_excl) if sub_in in i and sub_ex not in i]
print(res)

Output

['fee1.foo', 'fee2.foo']

Upvotes: 1

Related Questions