Reputation: 190
From the following list, i am trying to extract only digits(ints & floats) & versions nums (only separated by dots).
[u'3.1.1', u'3.2', u'3.1.2', u'3', u'3.3.0', u'3.3.1-1', u'3.2.2', u'latest']
Tried the following code. Its not taking out 3.3.1-1. Need help with regex. Also is there any fastest way to do it?
def myfunc(self, img_list):
ret = list()
for i in img_list:
try:
if re.match("([\d.]+)", i):
ret.append(i)
elif float(i):
ret.append(i)
except Exception as e:
display.vvv("Error: %s" % str(e))
pass
return ret
Upvotes: 1
Views: 80
Reputation: 1448
Just replace all . in the string and check if remaining characters are digits.
def myfunc(self , img_list):
ret = list()
for i in img_list:
if '.' in i and i.replace('.','').isdigit():
ret.append(i)
return ret
Upvotes: 0
Reputation: 2055
Another solution using comprehension:
lst = [u'3.1.1', u'3.2', u'3.1.2', u'3', u'3.3.0', u'3.3.1-1', u'3.2.2', u'latest']
results = [i for i in lst if i.replace('.', '').isdigit()]
print results
output:
[u'3.1.1', u'3.2', u'3.1.2', u'3', u'3.3.0', u'3.2.2']
Upvotes: 1
Reputation: 6748
You could try a list comprehension.
lst = [u'3.1.1', u'3.2', u'3.1.2', u'3', u'3.3.0', u'3.3.1-1', u'3.2.2', u'latest']
print([e for e in lst if ''.join(e.split('.')).isdigit()])
Prints:
['3.1.1', '3.2', '3.1.2', '3', '3.3.0', '3.2.2']
Upvotes: 0
Reputation: 2076
Regex is one way to go. You can accomplish the same using filter
>>> lst = [u'3.1.1', u'3.2', u'3.1.2', u'3', u'3.3.0', u'3.3.1-1', u'3.2.2', u'latest']
>>> list(filter(lambda s: all(c.isdigit() or c == "." for c in s), lst))
['3.1.1', '3.2', '3.1.2', '3', '3.3.0', '3.2.2']
Upvotes: 0