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.

1
  • You can you 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 Commented Aug 5, 2018 at 19:50

1 Answer 1

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']
Sign up to request clarification or add additional context in comments.

2 Comments

What about '1e+10' for example? Also negative numbers.
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 comes to mind here.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.