0

I have a list where each element is stored as a string

A = ['a', 'b', 'c', '100','200.6']

How can I extract only the numeric elements

[100, 200.6]

I cannot convert the elements using [float(i) for i in temp] as string elements cannot be converted to float. I need to retain the string elements as they are and just filter out the numeric elements.

marc
  • 949
  • 14
  • 33
  • You can you [`Filter`](https://www.programiz.com/python-programming/methods/built-in/filter) `def is_number(s): try: float(s) return True except ValueError: return False filter(is_number, A)` this is cleaner than adding your own for loop – Itamar Aug 05 '18 at 19:50

1 Answers1

0

For simple cases, you can use re.match to check if the element matches a number with decimal point and then convert it to a float

>>> A = ['a', 'b', 'c', '100', '200.6']
>>> import re
>>> [float(e) for e in A if re.match(r'\d+\.?\d*$', e)]
[100.0, 200.6]

But as folks have pointed out in the comments, if you floats in unconventional formats, you have to write a utility function to convert the string to float when possible or return None and then filter the list

>>> def is_float(n):
...     try:
...         return float(n)
...     except:
...         return None
... 
>>>
>>> A = ['a', 'b', 'c', '100', '200.6']
>>> list(filter(is_float, A))
['100', '200.6']
Sunitha
  • 11,777
  • 2
  • 20
  • 23
  • What about '1e+10' for example? Also negative numbers. – Andrej Kesely Aug 05 '18 at 19:48
  • This misses a large number of strings that can be converted to floats. By far the easiest and most robust option is attempting the cast, as shown in the duplicate. For example, in Python `'10_000'` can be cast to float. [This article](https://blog.codinghorror.com/regular-expressions-now-you-have-two-problems/) comes to mind here. – user3483203 Aug 05 '18 at 19:51