Simple Question:
list_1 = [ \'asdada\', 1, 123131.131, \'blaa adaraerada\', 0.000001, 34.12451235265, \'stackoverflow is awesome\' ]
I want
List comprehensions.
list_2 = [num for num in list_1 if isinstance(num, (int,float))]
list_2 = [i for i in list_1 if isinstance(i, (int, float))]
I think the easiest way is:
[s for s in myList if s.isdigit()]
Hope it helps!
All solutions proposed work only if the numbers inside the list are already converted to the appropriate type (int, float).
I found myself with a list coming from the fetchall function of sqlite3. All elements there were formated as str, even if some of those elements were actually integers.
cur.execute('SELECT column1 FROM table1 WHERE column2 = ?', (some_condition, ))
list_of_tuples = cur.fetchall()
The equivalent from the question would be having something like:
list_1 = [ 'asdada', '1', '123131', 'blaa adaraerada', '0', '34', 'stackoverflow is awesome' ]
For such a case, in order to get a list with the integers only, this is the alternative I found:
list_of_numbers = []
for tup in list_of_tuples:
try:
list_of_numbers.append(int(tup[0]))
except ValueError:
pass
list_of_numbers will contain only all integers from the initial list.
for short of SilentGhost way
list_2 = [i for i in list_1 if isinstance(i, (int, float))]
to
list_2 = [i for i in list_1 if not isinstance(i, str)]
filter(lambda n: isinstance(n, int), [1,2,"three"])