UberJumper
UberJumper

Reputation: 21145

List Comprehensions and Conditions?

I am trying to see if I can make this code better using list comprehensions.
Lets say that I have the following lists:

a_list = [
        'HELLO',
        'FOO',
        'FO1BAR',
        'ROOBAR',
        'SHOEBAR'
        ]

regex_list =   [lambda x: re.search(r'FOO', x, re.IGNORECASE),
                lambda x: re.search(r'RO', x, re.IGNORECASE)]

I basically want to add all the elements that do not have any matches in the regex_list into another list.

E.g. ==>

newlist = []
for each in a_list:
    for regex in regex_list:
        if(regex(each) == None):
            newlist.append(each)

How can I do this using list comprehensions? Is it even possible?

Upvotes: 7

Views: 7553

Answers (2)

johannix
johannix

Reputation: 29658

I'd work your code down to this:

a_list = [
          'HELLO',
          'FOO',
          'FO1BAR',
          'ROOBAR',
          'SHOEBAR'
          ]
regex_func = lambda x: not re.search(r'(FOO|RO)', x, re.IGNORECASE)    

Then you have two options:

  1. Filter

    newlist = filter(regex_func, a_list)

  2. List comprehensions

    newlist = [x for x in a_list if regex_func(x)]

Upvotes: 0

David Z
David Z

Reputation: 131550

Sure, I think this should do it

newlist = [s for s in a_list if not any(r(s) for r in regex_list)]

EDIT: on closer inspection, I notice that your example code actually adds to the new list each string in a_list that doesn't match all the regexes - and what's more, it adds each string once for each regex that it doesn't match. My list comprehension does what I think you meant, which is add only one copy of each string that doesn't match any of the regexes.

Upvotes: 18

Related Questions