-2

I want to extract only the numbers from a Python list where the input elements are str:

input_in_terminal = "5 43 8 109 32"

input_list = [5, ' ', 43, ' ', 8, ' ', 109, ' ', 32]

How can I extract only the numbers and create a list as below?

extracted_list = [5,43,8,109,32]
iacob
  • 20,084
  • 6
  • 92
  • 119
Marabe
  • 11
  • 1
  • 1
    `[i for i in input_list if i != ' ']` – user3483203 Jun 04 '18 at 22:23
  • 3
    How did you get `input_list` from the input typed into the terminal? It sounds like you're doing a bunch of work you don't need, just to keep the parts of the input you don't want. – user2357112 Jun 04 '18 at 22:25
  • 3
    But better to just use `list(map(int, input().split()))` – user3483203 Jun 04 '18 at 22:25
  • 1
    `[int(word) for word in line.split()]` is all you need to handle your input line. `[elem for elem in lst if isinstance(elem, int)]` will filter the list you say you have—but as user suggests you probably shouldn’t have that list in the first place. – abarnert Jun 04 '18 at 22:34
  • Unfortunately I can't change input_list but list(map(int, input().split())) worked! Thank you. – Marabe Jun 04 '18 at 22:36

1 Answers1

-1

Python 3:

extracted_list = list(filter(lambda x: x != ' ' , input_list))

or if you want to avoid multiple spaces check if it's an integer and filter out anything that's not an integer.

extracted_list = list(filter(lambda x: isinstance(x,int) , input_list))

If you need other kinds like float or complex you can do:

extracted_list = list(filter(lambda x: isinstance(x,(float,int,complex)) ,input_list))

speed: --- 6.818771362304688e-05 seconds ---

Or for any number

import numbers
input_list = [5, ' ', 43, ' ', 8, '   ', 109, ' ', 32, 3.14]
extracted_list = list(filter(lambda x: isinstance(x, numbers.Number) ,input_list))

print (extracted_list)

you can test it here: http://py3.codeskulptor.org/#user301_l6dgnVkb19Or9dN.py

Stofke
  • 2,928
  • 2
  • 21
  • 28