Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List filtering and transformation

I have a list of library filenames that I need to filter against regular expression and then extract version number from those that match. This is the obvious way to do that:

libs = ['libIce.so.33', 'libIce.so.3.3.1', 'libIce.so.32', 'libIce.so.3.2.0']
versions = []
regex = re.compile('libIce.so\.([0-9]+\.[0-9]+\.[0-9]+)')
for l in libs:
    m = regex.match(l)
    if m:
        versions.append(m.group(1))

That produces the following list:

['3.3.1', '3.2.0']

Yet I feel that loop is not very 'Python style' and feel it should be possible to replace 'for' loop above with some smart one-liner. Suggestions?

like image 367
Aleksei Potov Avatar asked Nov 03 '09 06:11

Aleksei Potov


2 Answers

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']
like image 98
Matt Anderson Avatar answered Oct 03 '22 16:10

Matt Anderson


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?

like image 21
Denis Otkidach Avatar answered Oct 03 '22 15:10

Denis Otkidach