Grep on elements of a list

Use filter():

>>> names = ['aet2000','ppt2000', 'aet2001', 'ppt2001']
>>> filter(lambda x:'aet' in x, names)
['aet2000', 'aet2001']

with regex:

>>> import re
>>> filter(lambda x: re.search(r'aet', x), names)
['aet2000', 'aet2001']

In Python 3 filter returns an iterator, hence to get a list call list() on it.

>>> list(filter(lambda x:'aet' in x, names))
['aet2000', 'aet2001']

else use list-comprehension(it will work in both Python 2 and 3:

>>> [name for name in names if 'aet' in name]
['aet2000', 'aet2001']

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)