Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 906
UberJumper Avatar asked May 05 '09 18:05

UberJumper


1 Answers

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.

like image 181
David Z Avatar answered Sep 23 '22 02:09

David Z