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?
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']
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With