Having fun with Python

I was doing some lightweight scripting like this:

pattern = re.compile("searchingFor", re.IGNORECASE)

tables = [];
for line in fp.readlines():
    if pattern.search(line):
        tables += line
return tables

And then I remembered how fun Python could be with things like the list comprehensions:

pattern = re.compile("searchingFor", re.IGNORECASE)
return [ line for line in fp.readlines()
                if pattern.search(line) ]

Nice, huh? If you want to find out more about mapping lists, keep reading here.

Update: Even better! Cleanear, intuitive, two liner… hell yeah!

pattern = re.compile("searchingFor", re.IGNORECASE)
return filter( pattern.search, fp.readlines() )

Compártelo
July 23rd, 2007 | Development, English, Python, Snippets |

Categories

Syndication

my favorite pictures

    Archives

    Cerrar
    Enviar por Correo