List filtering and transformation

How about a list comprehension?

In [5]: versions = [m.group(1) for m in [regex.match(lib) for lib in libs] if m] 
In [6]: versions
Out[6]: ['3.3.1', '3.2.0']

You could do this:

versions = [m.group(1) for m in [regex.match(l) for l in libs] if m]

I don't think it's very readable, though...

Maybe it's clearer done in two steps:

matches = [regex.match(l) for l in line]
versions = [m.group(1) for m in matches if m]

One more one-liner just to show other ways (I've also cleaned regexp a bit):

regex = re.compile(r'^libIce\.so\.([0-9]+\.[0-9]+\.[0-9]+)$')
sum(map(regex.findall, libs), [])

But note, that your original version is more readable than all suggestions. Is it worth to change?


There's nothing that isn't pythonic about using a standard for loop. However, you can use the map() function to generate a new list based on the results from a function run against each item in the list.