labmat labmat - 1 month ago 20
Python Question

Extract numbers from list: python

How should I extract numbers only from

a = ['1 2 3', '4 5 6', 'invalid']


I have tried:

mynewlist = [s for s in a if s.isdigit()]
print mynewlist


and

for strn in a:
values = map(float, strn.split())
print values


Both failed because there is a space between the numbers.

Note: I am trying to achieve output as:
[1, 2, 3, 4, 5, 6]

Answer

I think you need to process each item in the list as a split string on whitespace.

a = ['1 2 3', '4 5 6', 'invalid']
numbers = []
for item in a:
    for subitem in item.split():
        if(subitem.isdigit()):
            numbers.append(subitem)
print(numbers)

['1', '2', '3', '4', '5', '6']

Or in a neat and tidy comprehension:

[item for subitem in a for item in subitem.split() if item.isdigit()]