tags:

views:

443

answers:

2

I am trying to see if i can make thsi code more interesting/exciting using list comprehensions. Lets say i have the following lists defined:

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?

+9  A: 

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.

David Zaslavsky
Not the same behaviour as the code he gave since "each" will never be appended more than once as in the example. However, I believe this is what he actually wanted to achieve.
bayer
Thank you thats perfect.
UberJumper
One more question, if i were to lets say replace a_list with a function that returns a list. Will it only be called once? Or will it be called at every iteration?e.g.def returnalist(): return ['klsdfj', 'kldffjsdkl', 'hello', 'somethinghats']and did:newlist = [s for s in returnalist() if not any(r(s) for r in regex_list)]Would returnalist be called constantly?
UberJumper
It should only be called once, in this case. Although you could always try it and see ;-)
David Zaslavsky
David, thank You for showing me potential of any. I didn't used it before.
praavDa
A: 

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 comprehension

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